[ACCEPTED]-Removing a prefix from a string-string
The strip family treat the arg as a set of 2 characters to be removed. The default set 1 is "all whitespace characters".
You want:
if strg.startswith("0b1"):
strg = strg[3:]
No. Stripping removes all characters in 3 the sequence passed, not just the literal 2 sequence. Slice the string if you want to 1 remove a fixed length.
In Python 3.9 you can use bbn.removeprefix('0b1')
.
(Actually this question has 1 been mentioned as part of the rationale in PEP 616.)
This is the way lstrip
works. It removes any of the 4 characters in the parameter, not necessarily 3 the string as a whole. In the first example, since 2 the input consisted of only those characters, nothing 1 was left.
Lstrip is removing any of the characters 3 in the string. So, as well as the initial 2 0b1, it is removing all zeros and all ones. Hence 1 it is all gone!
@Harryooo: lstrip only takes the characters 5 off the left hand end. So, because there's 4 only one 1 before the first 0, it removes 3 that. If the number started 0b11100101...
, calling a.strip('0b').strip('1')
would 2 remove the first three ones, so you'd be 1 left with 00101
.
>>> i = 0b1000101110100010111010001
>>> print(bin(i))
'0b1000101110100010111010001'
>>> print(format(i, '#b'))
'0b1000101110100010111010001'
>>> print(format(i, 'b'))
'1000101110100010111010001'
From the standard doucmentation (See standard documentation for function bin()): bin(x) Convert 8 an integer number to a binary string prefixed 7 with “0b”. The result is a valid Python 6 expression. If x is not a Python int object, it 5 has to define an index() method that returns 4 an integer. Some examples:
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
If prefix “0b” is 3 desired or not, you can use either of the 2 following ways.
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
See also format() for more 1 information.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.