Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make `bin(30)` return `00011110` instead of `0b11110`? [duplicate]

Tags:

python

What does the "b" stand for in the output of bin(30): "0b11110"? Is there any way I can get rid of this "b"? How can I get the output of bin() to always return a standard 8 digit output?

like image 231
AME Avatar asked Sep 08 '09 17:09

AME


People also ask

Why does bin return 0b?

0b is like 0x - it indicates the number is formatted in binary (0x indicates the number is in hex).

Does bin () return a string?

The bin() method returns: the binary string equivalent to the given integer.

How do you remove 0b prefix in Python?

To remove the prefixed “0b” string, use array slicing on the string.

How do you specify binary in Python?

To assign value in binary format to a variable, we use the 0b suffix. It tells the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable. Note: To print value in binary format, we use bin() function.


1 Answers

Using zfill():

Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than len(s).

>>> bin(30)[2:].zfill(8) '00011110' >>> 
like image 154
gimel Avatar answered Sep 22 '22 09:09

gimel