Strip an ordered sequence of characters from a string

michaelmeyer picture michaelmeyer · Apr 8, 2013 · Viewed 8.3k times · Source

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 ?

Answer

bbayles picture bbayles · Apr 8, 2013

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'