Python int to binary string?


Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?

There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.

Answer rating: 927

Python"s string format method can take a format spec.

>>> "{0:b}".format(37)

Format spec docs for Python 2

Format spec docs for Python 3

Answer rating: 565

If you"re looking for bin() as an equivalent to hex(), it was added in python 2.6.


>>> bin(10)

Get Solution for free from DataCamp guru