Python:从某个字符开始替换字符串

4 投票
4 回答
13205 浏览
提问于 2025-04-17 14:48

我需要一个优化过的方法来替换字符串中从'/'开始的所有后续字符。

举个例子:

mytext = "this is my/string"

我想要的结果是这样的:

mytext = "this is my/text"

只有'/'后面的部分需要被替换,而且这个过程要尽量高效。有没有人能帮我找到解决方案?

4 个回答

0

正则表达式的速度比较慢,因为你需要在第一个 / 字符之后获取所有的文本。最好的做法是:

mytext[:mytext.index('/')+1] + 'the replacement text'

不过,如果没有 / 的话,这种方法就会失败。

6

我不太明白你说的“优化”是什么意思,不过我会这样做:

>>> import re
>>> mytext = "this is my/string"
>>> re.sub('/.*','/text',mytext)
'this is my/text'
3

这个看起来是最快的:

s = "this is my/string"
mytext = s[:s.rindex('/')] + '/text'

我测试过的内容:

>>> s = "this is my/string"
>>> pattern = re.compile('/.*$')

>>> %timeit pattern.sub('/text', s)
1000000 loops, best of 3: 730 ns per loop

>>> %timeit s[:s.rindex('/')] + '/text'
1000000 loops, best of 3: 284 ns per loop

>>> %timeit s.rsplit('/', 1)[0] + '/text'
1000000 loops, best of 3: 321 ns per loop

撰写回答