Python bin() built-in function

From the Python 3 documentation

Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

Introduction

The bin() function converts an integer into its binary representation. The resulting string is prefixed with “0b” to indicate that it’s a binary number.

Examples

Here are a few examples of how to use bin():

# Convert integers to binary
print(bin(2))    # Output: 0b10
print(bin(7))    # Output: 0b111
print(bin(1))    # Output: 0b1
print(bin(10))   # Output: 0b1010
print(bin(100))  # Output: 0b1100100
print(bin(1000)) # Output: 0b1111101000

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.