我有一个字符串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
?
发布于 2018-04-03 12:35:22
如果您阅读str.strip
的文档,您将看到:
chars参数是一个字符串,指定要删除的字符集。
因此,'.mainlog'
(['.', 'm', 'a', 'i', 'n', 'l', 'o', 'g']
)中的所有字符都是从开头和结尾开始和结束的。
您想要的是str.replace
将所有出现的'.mainlog'
替换为nothing:
s.replace('.mainlog', '')
#'ntm_MonMar26_16_59_41_2018'
发布于 2018-04-03 12:34:47
来自Python文档:
https://docs.python.org/2/library/string.html#string.strip
目前,它试图删除您提到的所有字符(“.”、“m”、“a”、“i”.)
您可以使用string.replace代替。
s.replace('.mainlog', '')
发布于 2018-04-03 12:34:32
你使用了错误的函数。strip
从字符串的开头和结尾删除字符。默认情况下,可以提供要删除的字符列表。
您应该使用:
s.replace('.mainlog', '')
或者:
import os.path
os.path.splitext(s)[0]
https://stackoverflow.com/questions/49638674
复制相似问题