How to convert a string of a binary number into a binary number?

Viewed 206
x = '0b001'

I need x to be 0b001 so that is a binary number, I tried doing int('0b001') however the 'b' gives an error due to being a character.

How to convert '0b001' into a binary?

2 Answers

If you want to get a decimal value of binary string, you can use int() with base argument set to 2.

x = '0b001'
decimal_x = int(x, 2)
decimal_x = 1

If you want to remove the '0b' from the binary string, do a string slice as below

x = '0b001'
x = x[2:]
x = '001'

Try specifying the base number to 0:

>>> int('0b001', 0)
1
>>> 
Related