Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 279
Nate Avatar asked Mar 31 '09 03:03

Nate


People also ask

How do you convert an integer to a binary string in Python?

To convert int to binary in Python, use the bin() method. The bin() is a built-in Python method that converts a decimal to a binary data type. The bin() function accepts a number as an argument and returns its equivalent binary string prefixed with “0b”.

Can you cast int to string in Python?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.


1 Answers

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

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

Format spec docs for Python 2

Format spec docs for Python 3

like image 137
Tung Nguyen Avatar answered Sep 22 '22 22:09

Tung Nguyen