Skip to main content
 首页 » 编程设计

python之在 python 中执行此字符串模式替换的最快方法是什么

2025年05月04日24Free-Thinker

给定一个 patten 中的字符串

str="a@b = c" 

想把它替换成

str="a@'b'" 

即,引用 'b' 并删除“=”及其自身之后的所有内容。

在 python 中执行此操作的最佳方法是什么?

编辑:

上面的'b'可以是任意长度的任意未知非空白字符串

请您参考如下方法:

"%s@'%s'"%tuple(txt.split(' =')[0].split('@')) 

只要 a 或 b 以 '@' 分隔且 c 以 '=' 分隔,它就可以使用任意值。

附言。如果 b 包含 '=' 或 '@',它会中断

编辑:添加基于 Green Cell 的速度基准。

edit_again:将其他示例添加到基准测试中。

import re 
 
import timeit 
 
# Method #1 (string ops) -> Green Cell's 
def stringOps(): 
    s="a@whammy = c" 
    replaceChar = s.split('@')[1].split(' ')[0]  
    s.split('=')[0].replace(replaceChar, "'{0}'".format(replaceChar) ).replace(' ', '') 
time1 = timeit.timeit('from __main__ import stringOps;stringOps()') 
# Method #2 (regex)  -> Dawg's  
def regex(): 
    s="a@bam = c" 
    re.sub(r'(\w+)(\s*=\s*\w+$)', r"'\1'", s) 
 
 
time2 = timeit.timeit('from __main__ import regex;regex()') 
 
#%method 3 split_n_dice  -> my own 
def slice_dice(): 
    txt="a@whammy = c" 
    "%s@'%s'"%tuple(txt.split(' =')[0].split('@')) 
 
time3 = timeit.timeit('from __main__ import slice_dice;slice_dice()')     
 
print 'Method #1 took {0}'.format(time1) 
print 'Method #2 took {0}'.format(time2) 
print 'Method #3 took {0}'.format(time3) 

Method #1 took 2.01555299759

Method #2 took 4.66884493828

Method #3 took 1.44083309174