Strange Python strip() behavior [duplicate]

匆匆过客 提交于 2021-02-05 11:15:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!