string.strip() 使用 python 2.7 和 3.5 时的奇怪错误

Odd bug in string.strip() using python 2.7 and 3.5

我在使用 string.strip() 进行的非常简单的字符串操作中得到了一些非常奇怪的结果。我想知道这是一个只影响我的问题(我的 python 安装有问题吗?)还是一个常见的错误?

这个错误非常有线,在这里:

>>> a = './omqbEXPT.pool'
>>> a.strip('./').strip('.pool')
'mqbEXPT' #the first 'o' is missing!!!

仅当 'o' 跟在 './' 后才会发生!

>>> a = './xmqbEXPT.pool'
>>> a.strip('./').strip('.pool')
'xmqbEXPT'

这是怎么回事?! 我已经在 python 2.7 和 3.5 上测试过,结果没有改变。

这就是 strip 方法实际设计的工作原理。

The chars argument is a string specifying the set of characters to be removed.

The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

所以当你说 my_string.strip('.pools') 时,它会删除该集合中的所有前导和尾随字符(即 {'.', 'p', 'o', 'l', 's'})。

您可能想使用 str.replace or re.sub

>>> './omqbEXPT.pool'.replace('./', '').replace('.pool', '')
'omqbEXPT'

>>> import re
>>> re.sub(r'^\.\/|\.pool$', '', './omgbEXPT.pool')
'omqbEXPT'

string.strip() 将左剥离和右剥离 每个字符 。意思是,当你要求它去除 pool 时,它会去除它在字符串两端找到的任何 ps 或 os 或 ls。这就是它剥离 o.

的原因

这不是错误。 strip 去除作为参数传递给它的字符串中的 任何 字符。因此,首先从字符串 a 中去除所有前导和尾随点和斜杠,然后去除字符串 '.pool' 包含的所有字符。