问题
I don't understand why the strip() function returns the way it does below. I want to strip() the last occurence of Axyx. I got around it by using rstrip('Axyx') but what's the explanation for the following?
>>>"Abcd Efgh Axyx".strip('Axyx')
'bcd Efgh '
回答1:
The string passed to strip
is treated as a bunch of characters, not a string. Thus, strip('Axyx')
means "strip occurrences of A
, x
, or y
from either end of the string".
If you actually want to strip a prefix or suffix, you'd have to write that logic yourself. For example:
s = 'Abcd Efgh Axyx'
if s.endswith('Axyx'):
s = s[:-len('Axyx')]
回答2:
Because strip() returns a copy of the string that you provided without the characters that you gave as input.
For example:
"12345".strip('123') returns: '45'.
So, strip() does not remove words or something but removes all the characters that the string that you give as input has, both from the end and the beginning of the string that you want to strip.
来源:https://stackoverflow.com/questions/33322112/strange-python-strip-behavior