6
votes

Trying to strip the "0b1" from the left end of a binary number.

The following code results in stripping all of binary object. (not good)

>>> bbn = '0b1000101110100010111010001' #converted bin(2**24+**2^24/11)
>>> aan=bbn.lstrip("0b1")  #Try stripping all left-end junk at once.
>>> print aan    #oops all gone.
''

So I did the .lstrip() in two steps:

>>> bbn = '0b1000101110100010111010001' #    Same fraction expqansion
>>> aan=bbn.lstrip("0b")# Had done this before.
>>> print aan    #Extra "1" still there.
'1000101110100010111010001'
>>> aan=aan.lstrip("1")#  If at first you don't succeed...
>>> print aan    #YES!
'000101110100010111010001'

What's the deal?

Thanks again for solving this in one simple step. (see my previous question)

7
Reading documentation helps ;) : The chars argument is not a prefix; rather, all combinations of its values are stripped. - Felix Kling
Similar to Why does str.lstrip strips an extra character? stackoverflow.com/questions/1687171/… - Steven Rumbalski

7 Answers

15
votes

The strip family treat the arg as a set of characters to be removed. The default set is "all whitespace characters".

You want:

if strg.startswith("0b1"):
   strg = strg[3:]
12
votes

No. Stripping removes all characters in the sequence passed, not just the literal sequence. Slice the string if you want to remove a fixed length.

5
votes

In Python 3.9 you can use bbn.removeprefix('0b1').

(Actually this question has been mentioned as part of the rationale in PEP 616.)

0
votes

This is the way lstrip works. It removes any of the characters in the parameter, not necessarily the string as a whole. In the first example, since the input consisted of only those characters, nothing was left.

0
votes

Lstrip is removing any of the characters in the string. So, as well as the initial 0b1, it is removing all zeros and all ones. Hence it is all gone!

0
votes

@Harryooo: lstrip only takes the characters off the left hand end. So, because there's only one 1 before the first 0, it removes that. If the number started 0b11100101..., calling a.strip('0b').strip('1') would remove the first three ones, so you'd be left with 00101.

0
votes
>>> i = 0b1000101110100010111010001
>>> print(bin(i))
'0b1000101110100010111010001'

>>> print(format(i, '#b'))
'0b1000101110100010111010001'
>>> print(format(i, 'b'))
'1000101110100010111010001'

See Example in python tutor:

From the standard doucmentation (See standard documentation for function bin()): bin(x) Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer. Some examples:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If prefix “0b” is desired or not, you can use either of the following ways.

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

See also format() for more information.