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 ?
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.
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.
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.
As of Python 3.9 you can use str.removeprefix and str.removesuffix.
From the docs:
'TestHook'.removeprefix('Test') # >> 'Hook'
'MiscTests'.removesuffix('Tests') # >> 'Misc'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With