Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip an ordered sequence of characters from a string

I've realized recently that the strip builtin of Python (and it's children rstrip and lstrip) does not treat the string that is given to it as argument as an ordered sequence of chars, but instead as a kind of "reservoir" of chars:

>>> s = 'abcfooabc'
>>> s.strip('abc')
'foo'
>>> s.strip('cba')
'foo'
>>> s.strip('acb')
'foo'

and so on.

Is there a way to strip an ordered substring from a given string, so that the output would be different in the above examples ?

like image 985
michaelmeyer Avatar asked Apr 08 '13 01:04

michaelmeyer


People also ask

How do I strip a character from a string?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

What does Strip () Python do?

The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.

How do you strip a character from a string in Python?

Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.


2 Answers

As of Python 3.9 you can use str.removeprefix and str.removesuffix.

From the docs:

'TestHook'.removeprefix('Test')  # >> 'Hook'
'MiscTests'.removesuffix('Tests')  # >> 'Misc'
like image 90
jtschoonhoven Avatar answered Oct 02 '22 13:10

jtschoonhoven


I had this same problem when I first started.

Try str.replace instead?

>>> s = 'abcfooabc'
>>> s.replace("abc", "")
0: 'foo'
>>> s.replace("cba", "")
1: 'abcfooabc'
>>> s.replace("acb", "")
2: 'abcfooabc'
like image 43
bbayles Avatar answered Oct 02 '22 13:10

bbayles