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

2024-10-04 11:26:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串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


Tags: 字符串reruntmstripntmmainlogrerumonmar26
3条回答

来自Python文档:

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

当前,它尝试剥离您提到的所有字符('.'、'm'、'a'、'i'…)

可以改用string.replace

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

如果您阅读^{}的文档,您将看到:

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

因此'.mainlog'['.', 'm', 'a', 'i', 'n', 'l', 'o', 'g'])中的所有字符都从开头和结尾剥离


您想要的是^{}将所有出现的'.mainlog'替换为空:

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

您使用了错误的函数strip删除字符串开头和结尾的字符。默认情况下为空格,但可以提供要删除的字符列表

您应该使用:

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

或:

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

相关问题 更多 >