Convert binary string to binary literal

前端 未结 2 548
后悔当初
后悔当初 2020-12-20 13:40

I\'m using Python 3.2.2.

I\'m looking for a function that converts a binary string, e.g. \'0b1010\' or \'1010\', into a binary literal, e.g. 0b1010 (not a string or

相关标签:
2条回答
  • 2020-12-20 13:42

    Try the following code:

    #!python3
    
    def fn(s, base=10):
        prefix = s[0:2]
        if prefix == '0x':
            base = 16
        elif prefix == '0b':
            base = 2
        return bin(int(s, base))
    
    
    print(fn('15'))
    print(fn('0xF'))
    print(fn('0b1111'))
    

    If you are sure you have s = "'0b010111'" and you only want to get 010111, then you can just slice the middle like:

    s = s[2:-1]
    

    i.e. from index 2 to the one before the last.

    But as Ignacio and Antti wrote, numbers are abstract. The 0b11 is one of the string representations of the number 3 the same ways as 3 is another string representation of the number 3.

    The repr() always returns a string. The only thing that can be done with the repr result is to strip the apostrophes -- because the repr adds the apostrophes to the string representation to emphasize it is the string representation. If you want a binary representation of a number (as a string without apostrophes) then bin() is the ultimate answer.

    0 讨论(0)
  • 2020-12-20 14:05

    The string is a literal.

    3>> bin(int('0b1010', 2))
    '0b1010'
    3>> bin(int('1010', 2))
    '0b1010'
    3>> 0b1010
    10
    3>> int('0b1010', 2)
    10
    
    0 讨论(0)
提交回复
热议问题