从字符串中删除子字符串时出现意外结果

Unexpected result when removing substring from a string

我有一个字符串 s,我想从中删除 '.mainlog'。我试过了:

>>> s = 'ntm_MonMar26_16_59_41_2018.mainlog'
>>> s.strip('.mainlog')
'tm_MonMar26_16_59_41_2018'

为什么 n'ntm...' 中删除?

同样,我还有一个问题:

>>> s = 'MonMar26_16_59_41_2018_rerun.mainlog'
>>> s.strip('.mainlog')
'MonMar26_16_59_41_2018_reru'

为什么 python 坚持要从我的字符串中删除 n?如何从我的字符串中正确删除 .mainlog

您使用了错误的功能。 strip 删除字符串开头和结尾的字符。默认为空格,但您可以给出要删除的字符列表。

您应该改用:

s.replace('.mainlog', '')

或者:

import os.path
os.path.splitext(s)[0]

来自 Python 文档:

https://docs.python.org/2/library/string.html#string.strip

目前,它试图去除您提到的所有字符 ('.', 'm', 'a', 'i'...)

您可以使用 string.replace。

s.replace('.mainlog', '')

如果您阅读 str.strip 的文档,您会看到:

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

因此 '.mainlog' (['.', 'm', 'a', 'i', 'n', 'l', 'o', 'g']) 中的所有字符都从头到尾被删除。


您想要的是 str.replace 将所有出现的 '.mainlog' 替换为空:

s.replace('.mainlog', '')
#'ntm_MonMar26_16_59_41_2018'

strip 函数的参数,在本例中,.mainlog 不是字符串,而是一组单独的字符。

这就是删除该列表中的所有前导和尾随字符。

如果我们传入参数 aiglmno.,我们会得到相同的结果。