For example, if I do this str(bin(66))
I get 0b1000010
, but if I do this str(bin(66)).strip("0b")
, I get 100001
(notice the missing '0').
I think I'm misusing the strip function.
strip
strips characters from both sides. Use lstrip
to only strip characters from the left-hand side.
In [27]: str(bin(66)).strip("0b")
Out[27]: '100001'
In [28]: str(bin(66)).lstrip("0b")
Out[28]: '1000010'
Alternatively, just use the format
method:
In [38]: '{:b}'.format(66)
Out[38]: '1000010'
From docs :
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix ; rather, all combinations of its values are stripped
So, you're thinking that str.strip
will remove the prefix "0b"
, but it doesn't work that way. It simply considers '0'
and 'b'
as two different characters and removes them from the start and end of the string. Same thing applies to both str.rstrip
and str.lstrip
they don't remove prefix or suffix, but combination of individual characters.
For example:
>>> "0b00101".lstrip("0b") #just an example case, removes more than just "0b"
'101'
Another example:
>>> strs = "foofoofoobarfoo"
>>> strs.lstrip('fo')
'barfoo'
>>> if strs.startswith('fo'): #this works fine
print strs.replace('fo','',1)
...
ofoofoobarfoo
For binary numbers apart from solutions suggested by @unutbu, you can also try slicing
:
>>> str(bin(66))[2:]
'1000010'
or format
:
>>> format(66, 'b')
'1000010'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.