我需要一种优化的方法来替换字符串中从“/”开始的所有尾随字符。
例如:
mytext = "this is my/string"
我想要这样的结果
mytext = "this is my/text"
只有'/'之后的字符串必须被替换并且必须以优化的方式完成。谁能为我找到解决方案?
我不确定您所说的优化是什么意思,但我会这样做:
>>> import re
>>> mytext = "this is my/string"
>>> re.sub('/.*','/text',mytext)
'this is my/text'
这似乎是最快的:
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
正则表达式 速度很慢,因为您需要(第一个?)/
字符之后的所有文本,所以最好的方法是:
mytext[:mytext.index('/')+1] + 'the replacement text'
但是,如果您没有“/”,这将失败。
不确定它有多快,也没有错误检查,但我会找到斜线并组合字符串。
s = 'this is my/string'
result = s[:s.find('/')+1]+'text'