how to format binary in python code example

Example 1: convert int to binary python

# Python program to convert decimal to binary 
    
# Function to convert Decimal number  
# to Binary number  
def decimalToBinary(n):  
    return bin(n).replace("0b", "")  
    
# Driver code  
if __name__ == '__main__':  
    print(decimalToBinary(8))  
    print(decimalToBinary(18))  
    print(decimalToBinary(7))  
    
Output:
1000
1001

Example 2: format binary string python

x = 10
print(format(x, '#b')) # 0b1010
print(format(x, 'b')) # 1010
x= 0xF
print(format(x, 'b')) # 1111
print(f'{x:b}') # 1111 (If you knew this format, you are Python Ninja!)

Example 3: format binary string python

>>> format(14, '#010b')
'0b00001110'