Remove the 0b in binary
31,972
Solution 1
Use slice operation to remove the first two characters.
In [1]: x = 17
In [2]: y = bin(x)[2:]
In [3]: y
Out[3]: '10001'
Solution 2
It's easy just make this function:
def f(n):print('{:0b}'.format(n))
f(17)
>>> 10001
Solution 3
use python string slice
operation.
a = bin(17)
b = bin(17)[2:]
to format this to 8-bits use zfill
.
c = b.zfill(8)
Solution 4
format(17, 'b')
>>> '10001'
Use the format()
builtin. It also works for hexadecimal, simply replace 'b'
with 'x'
.
https://docs.python.org/3/library/functions.html#format
Solution 5
with Python 3.6 you can use f-strings
print( f'{x:b}' )
'10001'
Author by
VChocolate
Updated on June 30, 2021Comments
-
VChocolate almost 3 years
I am trying to convert a binary number I have to take out the 0b string out.
I understand how to get a bin number
x = 17 print(bin(17)) '0b10001'
but I want to take the
0b
in the string out and I am having some issues with doing this. This is going to be within a function returning a binary number without the0b
. -
mbpaulus over 5 yearsbeware, for 0 this returns an empty string.
-
NikT almost 3 yearshexadecimal is 'x', not 'h' -- for all specifiers, see docs.python.org/3/library/…