89DEVs

Python: How to use bin() function without 0b?

How to use the bin() function without 0b?

To use the bin() function without 0b in Python we have to remove the prefix. The prefix 0b is added by bin() to indicate a binary representation. To remove it, we can choose between one of the following options.
  1. slice notations
  2. string.replace()
  3. regex

slice notations

To remove the 0b prefix, use slice notations and slice the first two characters off. # remove 0b prefix using slice notations myInt = 5 myBin = bin(myInt) print(myBin[2:]) The bin() function returns a prefix in the first two positions. [2:] returns the binary without the prefix. 101

string.replace() method

To replace the prefix 0b, use the replace() method of string objects. # remove 0b prefix using string.replace() method myInt = 5 myBin = bin(myInt) myBin = myBin.replace('0b', '') print(myBin) The prefix is replaced by an empty string and therefore removed from the binary representation. 101

Regex

To remove the prefix 0b, use the sub() function of re - the regex module in Python. # remove 0b prefix using regex import re myInt = 5 myBin = bin(myInt) myBin = re.sub('0b', '', myBin) print(myBin) The 0b is replaced by an empty string and therefore removed from our binary representation. 101

                
        

Summary


Click to jump to section