ale*_*inn 1 python string strip
在使用 string.strip() 进行非常简单的字符串操作时,我得到了一些非常奇怪的结果。我想知道这是一个只影响我的问题(我的 python 安装有问题?)还是一个常见的错误?
这个错误是非常有线的,它是这样的:
>>> a = './omqbEXPT.pool'
>>> a.strip('./').strip('.pool')
'mqbEXPT' #the first 'o' is missing!!!
Run Code Online (Sandbox Code Playgroud)
仅当 'o' 跟在 './' 之后时才会发生!
>>> a = './xmqbEXPT.pool'
>>> a.strip('./').strip('.pool')
'xmqbEXPT'
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?!我已经在 python 2.7 和 3.5 上对此进行了测试,结果没有改变。
这就是该strip方法的实际设计方式。
chars 参数是一个字符串,指定要删除的字符集。
chars 参数不是前缀或后缀;相反,它的值的所有组合都被剥离了:
因此,当您说 时my_string.strip('.pools'),它将删除该集合中的所有前导和尾随字符(即。{'.', 'p', 'o', 'l', 's'})。
您可能想要使用str.replace或re.sub。
>>> './omqbEXPT.pool'.replace('./', '').replace('.pool', '')
'omqbEXPT'
>>> import re
>>> re.sub(r'^\.\/|\.pool$', '', './omgbEXPT.pool')
'omqbEXPT'
Run Code Online (Sandbox Code Playgroud)