W3docs

Python int to binary string?

You can use the built-in bin() function to convert an integer to a binary string in Python.

You can use the built-in bin() function to convert an integer to a binary string in Python. Here is an example:

Convert an integer to a binary string in Python

x = 5
binary_string = bin(x)
print(binary_string)

Output:

output

'0b101'

Note that the result will include the prefix '0b' indicating that the value is in binary representation. If you want to remove this prefix, you can use string slicing like this:

Remove '0b' prefix with slicing

x = 5
binary_string = bin(x)[2:]
print(binary_string)

Output:

another output

'101'

You can also use the format method to achieve the same

String format method in Python

x = 5
binary_string = format(x,'b')
print(binary_string)

Output:

the same output

'101'