简体   繁体   中英

Convert binary string to binary literal

I'm using Python 3.2.2.

I'm looking for a function that converts a binary string, eg '0b1010' or '1010', into a binary literal, eg 0b1010 (not a string or a decimal integer literal).

It's an easy matter to roll-my-own, but I prefer to use either a standard function or one that is well-established: I don't want to 're-invent the wheel.'

Regardless, I'm happy look at any efficient algorithms y'all might have.

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

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]

ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM