How To Use Text Strip() Function?
I can strip numerics but not alpha characters: >>> text '132abcd13232111' >>> text.strip('123') 'abcd' Why the following is not working? >>> text.strip
Solution 1:
The reason is simple and stated in the documentation of strip
:
str.strip([chars])
Return a copy of the stringwith the leading and trailing characters removed.
The chars argument is a string specifying the setof characters to be removed.
'abcd'
is neither leading nor trailing in the string '132abcd13232111'
so it isn't stripped.
Solution 2:
Just to add a few examples to Jim's answer, according to .strip()
docs:
- Return a copy of the string with the leading and trailing characters removed.
- The chars argument is a string specifying the set of characters to be removed.
- If omitted or None, the chars argument defaults to removing whitespace.
- The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.
So it doesn't matter if it's a digit or not, the main reason your second code didn't worked as you expected, is because the term "abcd" was located in the middle of the string.
Example1:
s = '132abcd13232111'print(s.strip('123'))
print(s.strip('abcd'))
Output:
abcd
132abcd13232111
Example2:
t = 'abcd12312313abcd'print(t.strip('123'))
print(t.strip('abcd'))
Output:
abcd12312313abcd
12312313
Post a Comment for "How To Use Text Strip() Function?"