This post will discuss how to convert an integer to a binary string in Python.

1. Using str.format() function

A simple solution is to use the str.format() function, which performs a string formatting operation. To convert the integer to its binary representation, you can use the string presentation type b.

Download  Run Code

 
To get the binary string of specified length left-padded with all zeros, you can change the formatting specification to {0:08b}:

Download  Run Code

2. Using f-strings

Starting with Python 3.6, you can use f-strings. This can be done by prefixing the string literal with f or F. Here’s how the code would look like:

Download  Run Code

3. Using format() built-in function

Another option is to use the built-in function format(value[, format_spec]) which converts the specified value to a formatted string according to the formatting specification format_spec. Here’s an example of its usage:

Download  Run Code

4. Using bin() built-in function

Finally, you may use the built-in function bin(), which converts an integer to a binary string prefixed with 0b. You can use slicing to get rid of the prefix, as shown below:

Download  Run Code

 
To get the binary string of specified length left-padded with zeros, you can use the zfill() function:

Download  Run Code

That’s all about converting an integer to a binary string in Python.