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
  • 12,225
  • 19
  • 71
  • 86
Evan_HZY
  • 984
  • 5
  • 17
  • 34

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
  • 232,561
  • 37
  • 312
  • 386
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
  • 244,495
  • 58
  • 464
  • 504
2
>>> from ast import literal_eval
>>> literal_eval("0b011")
3
John La Rooy
  • 295,403
  • 53
  • 369
  • 502