Using a tuple efficiently with stripe ()
Consider the basic tuple
one used with the inline method str.startswith()
:
>>> t = 'x','y','z'
>>> s = 'x marks the spot'
>>> s.startswith( t )
True
It seems like a loop is needed 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'
It seems wasteful; is there a more efficient way to use tuple elements with str.strip()
? s.strip(t)
it seemed logical, however, there was no bueno.
source to share
Disabling a string is a very different matter from testing if the string starts with a given text, so the methods are significantly different from how they handle their input.
str.strip()
takes one string, which is treated as a set of characters; the string will be stripped of each of these characters in the set; as long as the string begins with a character that is a member of the set, the start or end character is removed, until there are no characters from the specified set at the beginning and end.
If you have a tuple, concatenate it on one line:
s.strip(''.join(t))
or pass it as a string literal:
s.strip('xyz')
Note that this means something different from being used str.strip()
with every single element of the tuple!
For comparison:
>>> 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 calls str.strip()
to a single character, it still won't produce the same result, because calling str.strip()
:
>>> for t in ('x', 'y', 'z'):
... s = s.strip(t)
...
>>> print(s)
xz_middle_zx
because the line never began or ended at x
or z
when those characters were removed; x
only ended at the beginning and at the end because the character y
was removed in the next step.
source to share