2

I'm trying to convert a string into a binary integer:

string = "0b011" 
i = int(string)

But this code raises a ValueError. However, the following code works fine:

i = int(0b011)

But here I've passed a binary literal, not a string. How do I convert a string?

Jason Sundram
  • 11,598
  • 19
  • 69
  • 86
Evan_HZY
  • 944
  • 4
  • 16
  • 33

3 Answers3

3

Try this code:

string = '0b011'
i = int(string, 2) # value of i is 3

It uses the built-in procedure int() with the optional base parameter, which indicates the base to be used in the conversion - two in this case, from the documentation:

The base parameter gives the base for the conversion (which is 10 by default) and may be any integer in the range [2, 36], or zero. If base is zero, the proper radix is determined based on the contents of string; the interpretation is the same as for integer literals.

Óscar López
  • 225,348
  • 35
  • 301
  • 374
2

use the second optional argument(base), to tell int() that the string is of base 2:

int(str[,base])

>>> string = "0b011"
>>> int(string,2)
3
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
2
>>> from ast import literal_eval
>>> literal_eval("0b011")
3
John La Rooy
  • 281,034
  • 50
  • 354
  • 495