Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a prefix from a string

Tags:

python

string

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)

like image 421
Harryooo Avatar asked Nov 10 '10 20:11

Harryooo


People also ask

How do I remove a prefix from a string in Python?

There are multiple ways to remove whitespace and other characters from a string in Python. The most commonly known methods are strip() , lstrip() , and rstrip() . Since Python version 3.9, two highly anticipated methods were introduced to remove the prefix or suffix of a string: removeprefix() and removesuffix() .

How do you remove a prefix in C++?

This can be achieved using C++20 std::string. starts_with() or std::string::substr function. That's all about removing the prefix from a string in C++.

What is remove prefix?

Python String removeprefix() function removes the prefix and returns the rest of the string. If the prefix string is not found, then it returns the original string. It is introduced in Python 3.9. 0 version.


3 Answers

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:]
like image 111
John Machin Avatar answered Oct 26 '22 15:10

John Machin


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.

like image 24
Ignacio Vazquez-Abrams Avatar answered Oct 26 '22 15:10

Ignacio Vazquez-Abrams


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

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

like image 22
AXO Avatar answered Oct 26 '22 16:10

AXO