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 the 0b
.
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'
use python string slice
operation.
a = bin(17)
b = bin(17)[2:]
to format this to 8-bits use zfill
.
c = b.zfill(8)
It's easy just make this function:
def f(n):print('{:0b}'.format(n))
f(17)
>>> 10001
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
with Python 3.6 you can use f-strings
print( f'{x:b}' )
'10001'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With