Consider a basic tuple used with the built-in method str.startswith():
>>> t = 'x','y','z'
>>> s = 'x marks the spot'
>>> s.startswith( t )
True
It seems a loop is required when using a tuple with str.strip():
>>> for i in t: s.strip(i)
...
' marks the spot'
'x marks the spot'
'x marks the spot'
This seems wasteful perhaps; is there a more efficient way to use tuple items with str.strip()? s.strip(t) seemed logical, however, no bueno.
Stripping a string is a very different usecase from testing if a string starts with a given text, so the methods differ materially in how they treat their input.
str.strip() takes one string, which is treated as a set of characters; the string will be stripped of each of those characters in the set; as long as the string starts of ends with a character that is a member of the set, that starting or ending character is removed, until start and end are free of any characters from the given set.
If you have a tuple join it into one string:
s.strip(''.join(t))
or pass it in as a string literal:
s.strip('xyz')
Note that this means something different from using str.strip() with each individual tuple element!
Compare:
>>> s = 'yxz_middle_zxy'
>>> for t in ('x', 'y', 'z'):
... print(s.strip(t))
...
yxz_middle_zxy
xz_middle_zx
yxz_middle_zxy
>>> print(s.strip('xyz'))
_middle_
Even if you chained the str.strip() calls with individual character, it would still not produce the same output because the str.strip() call:
>>> for t in ('x', 'y', 'z'):
... s = s.strip(t)
...
>>> print(s)
xz_middle_zx
because the string never started or ended in x or z when those character were stripped; x only ended up at the start and end because the y character was stripped in a next step.
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