str.strip()中的多字符操作问题



我已经阅读了带有regex过滤意外字符的post-Python str.strip((和官方文档(这是针对Python 2的,但在Python 3中,它已经不存在了(。

我有点困惑。因此,我做了如下实验。

>>> 'hello'.strip('o')
'hell'
>>> 'hello.hello'.strip('.hello')
''
>>> 'hello.hello'.strip('.o')
'hello.hell'
>>> 'hello.hello'.strip('o.')
'hello.hell'
>>> 'Hello.hello'.strip('H')
'ello.hello'
>>> 'Hello.hello'.strip('H.')
'ello.hello'
>>> 'HEllo.hello'.strip('E')
'HEllo.hello'
>>> 'HEllo.hEllo'.strip('E')
'HEllo.hEllo'
>>> 'HEllo.hEllo'.strip('HE')
'llo.hEllo'
>>> 'HEllo.hEllo'.strip('El')
'HEllo.hEllo'
>>> 'HEllo.hEllo'.strip('Eo')
'HEllo.hEll'
>>> 'HEllo.hEllo'.strip('.h')
'HEllo.hEllo'
>>> 'HEllo.hEllo'.strip('o.h')
'HEllo.hEll'
>>> 'HEllo.hEllo'.strip('o-h')
'HEllo.hEll'
>>> 'HEllo.hEllo'.strip('hello')
'HEllo.hE'
>>> 'hello.hello'.strip('hello')
'.'

我不知道上面的一些结果。

有人能给我一个解释吗?

为什么要从python 3文档中删除此区域?

基本上,.strip()将字符串参数视为一组字符。然后,它转到字符串的开头和结尾,并删除在集合中找到的字符,直到找到不在集合中的字符为止。考虑一下:

>>> '#TEST#'.strip('#') # strips the #'s at the front and end
'TEST'
>>> '#TEST#'.strip('#T') # strips T's and #'s off of the front and end 
'ES'
>>> '#TEST#'.strip('T#') # the order of the chars in the argument doesn't matter
'ES'
>>> '#TEST#'.strip('#ES') # removes the #'s, but not the E or S as the T's "obstruct" strip()
'TEST'
>>> '#TEST#'.strip('T') # will remove nothing, as the #'s "obstruct" strip()
'#TEST#'

此外,正如Mark Meyer所指出的,这些文档可以在https://docs.python.org/3.7/library/stdtypes.html#str.strip.

最新更新