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 ?
I don't know of a built-in way, no, but it's pretty simple:
def strip_string(string, to_strip):
if to_strip:
while string.startswith(to_strip):
string = string[len(to_strip):]
while string.endswith(to_strip):
string = string[:-len(to_strip)]
return string