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

标签 python

给定一个 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

关于python - 在 python 中执行此字符串模式替换的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32388946/

相关文章:

python - 计算特定值的两个二维二进制 numpy 数组的重叠值

python - Django 和 Github 上的数据库管理

python - 将附加参数传递给 Pandas 自定义访问器

python - 如何使用 python sdk 访问 Azure 存储表中的最新条目?

python - 如何打印Python字符串的某些部分?

python - 复制列表 : editing copy without changing original

Python Tkinter - 在运行时更新

python - 抓取网页以获取图像 url

python - 这是引发异常的正确方法吗? ( python )

javascript - JQuery/Django 有办法构建 "click the text to edit"吗?