替换字符串中多个字符的最佳方法?

新手上路,请多包涵

I need to replace some characters as follows: &\& , #\# , …

我编码如下,但我想应该有更好的方法。有什么提示吗?

 strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...

原文由 prosseek 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 461
2 个回答

替换两个字符

我对当前答案中的所有方法以及一个额外的方法进行了计时。

使用 abc&def#ghi 的输入字符串并替换 & -> \& 和 # -> \#,最快的方法是像这样将替换链接在一起: text.replace('&', '\&').replace('#', '\#')

每个函数的时间:

  • a) 1000000 个循环,最好的 3 个:每个循环 1.47 μs
  • b) 1000000 个循环,最好的 3 个:每个循环 1.51 μs
  • c) 100000 个循环,最好的 3 个:每个循环 12.3 μs
  • d) 100000 个循环,最好的 3 个循环:每个循环 12 μs
  • e) 100000 个循环,最好的 3 个:每个循环 3.27 μs
  • f) 1000000 个循环,最好的 3 个:每个循环 0.817 μs
  • g) 100000 个循环,最好的 3 个:每个循环 3.64 μs
  • h) 1000000 个循环,最好的 3 个:每个循环 0.927 μs
  • i) 1000000 个循环,最好的 3 个:每个循环 0.814 μs

以下是功能:

 def a(text):
    chars = "&#"
    for c in chars:
        text = text.replace(c, "\\" + c)

def b(text):
    for ch in ['&','#']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)

import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)

RX = re.compile('([&#])')
def d(text):
    text = RX.sub(r'\\\1', text)

def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
    esc(text)

def f(text):
    text = text.replace('&', '\&').replace('#', '\#')

def g(text):
    replacements = {"&": "\&", "#": "\#"}
    text = "".join([replacements.get(c, c) for c in text])

def h(text):
    text = text.replace('&', r'\&')
    text = text.replace('#', r'\#')

def i(text):
    text = text.replace('&', r'\&').replace('#', r'\#')

时间是这样的:

 python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"


替换 17 个字符

下面是执行相同操作但需要转义更多字符的类似代码 (\`*_{}>#+-.!$):

 def a(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)

def b(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)

import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)

RX = re.compile('([\\`*_{}[]()>#+-.!$])')
def d(text):
    text = RX.sub(r'\\\1', text)

def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('\\`*_{}[]()>#+-.!$')
def e(text):
    esc(text)

def f(text):
    text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')

def g(text):
    replacements = {
        "\\": "\\\\",
        "`": "\`",
        "*": "\*",
        "_": "_",
        "{": "\{",
        "}": "\}",
        "[": "\[",
        "]": "\]",
        "(": "\(",
        ")": "\)",
        ">": "\>",
        "#": "\#",
        "+": "\+",
        "-": "\-",
        ".": "\.",
        "!": "\!",
        "$": "\$",
    }
    text = "".join([replacements.get(c, c) for c in text])

def h(text):
    text = text.replace('\\', r'\\')
    text = text.replace('`', r'\`')
    text = text.replace('*', r'\*')
    text = text.replace('_', r'_')
    text = text.replace('{', r'\{')
    text = text.replace('}', r'\}')
    text = text.replace('[', r'\[')
    text = text.replace(']', r'\]')
    text = text.replace('(', r'\(')
    text = text.replace(')', r'\)')
    text = text.replace('>', r'\>')
    text = text.replace('#', r'\#')
    text = text.replace('+', r'\+')
    text = text.replace('-', r'\-')
    text = text.replace('.', r'\.')
    text = text.replace('!', r'\!')
    text = text.replace('$', r'\$')

def i(text):
    text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')

以下是相同输入字符串 abc&def#ghi 的结果:

  • a) 100000 个循环,最好的 3 个:每个循环 6.72 μs
  • b) 100000 次循环,最好是 3 次:每次循环 2.64 μs
  • c) 100000 个循环,最好的 3 个:每个循环 11.9 μs
  • d) 100000 个循环,最好的 3 个循环:每个循环 4.92 μs
  • e) 100000 个循环,最好的 3 个:每个循环 2.96 μs
  • f) 100000 个循环,最好的 3 个:每个循环 4.29 μs
  • g) 100000 个循环,最好的 3 个:每个循环 4.68 μs
  • h) 100000 个循环,最好的 3 个:每个循环 4.73 μs
  • i) 100000 个循环,最好的 3 个循环:每个循环 4.24 μs

并使用更长的输入字符串( ## *Something* and [another] thing in a longer sentence with {more} things to replace$ ):

  • a) 100000 个循环,最好的 3 个:每个循环 7.59 μs
  • b) 100000 个循环,最好的 3 个:每个循环 6.54 μs
  • c) 100000 次循环,最好是 3 次:每次循环 16.9 μs
  • d) 100000 个循环,最好的 3 个:每个循环 7.29 μs
  • e) 100000 个循环,最好的 3 个:每个循环 12.2 μs
  • f) 100000 个循环,最好的 3 个:每个循环 5.38 μs
  • g) 10000 个循环,最好的 3 个循环:每个循环 21.7 μs
  • h) 100000 个循环,最好的 3 个:每个循环 5.7 μs
  • i) 100000 个循环,最好的 3 个循环:每个循环 5.13 μs

添加几个变体:

 def ab(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        text = text.replace(ch,"\\"+ch)

def ba(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        if c in text:
            text = text.replace(c, "\\" + c)

输入较短:

  • ab) 100000 个循环,最好的 3 个:每个循环 7.05 μs
  • ba) 100000 个循环,最好的 3 个循环:每个循环 2.4 μs

使用更长的输入:

  • ab) 100000 个循环,最好的 3 个:每个循环 7.71 μs
  • ba) 100000 个循环,最好的 3 个:每个循环 6.08 μs

所以我将使用 ba 以提高可读性和速度。

附录

由评论中的 hacks 提示, abba 之间的一个区别是 if c in text: 检查。让我们针对另外两个变体测试它们:

 def ab_with_check(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)

def ba_without_check(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)

在 Python 2.7.14 和 3.6.3 上每个循环的时间以 μs 为单位,并且在与早期设置不同的机器上,因此不能直接比较。

 ╭────────────╥──────┬───────────────┬──────┬──────────────────╮
│ Py, input  ║  ab  │ ab_with_check │  ba  │ ba_without_check │
╞════════════╬══════╪═══════════════╪══════╪══════════════════╡
│ Py2, short ║ 8.81 │    4.22       │ 3.45 │    8.01          │
│ Py3, short ║ 5.54 │    1.34       │ 1.46 │    5.34          │
├────────────╫──────┼───────────────┼──────┼──────────────────┤
│ Py2, long  ║ 9.3  │    7.15       │ 6.85 │    8.55          │
│ Py3, long  ║ 7.43 │    4.38       │ 4.41 │    7.02          │
└────────────╨──────┴───────────────┴──────┴──────────────────┘

我们可以得出结论:

  • 有检查的人比没有检查的人快 4 倍

  • ab_with_check 在 Python 3 上略微领先,但 ba (带检查)在 Python 2 上领先更多

  • 然而,这里最大的教训是 Python 3 比 Python 2 快 3 倍! Python 3 上最慢的和 Python 2 上最快的之间没有太大区别!

原文由 Hugo 发布,翻译遵循 CC BY-SA 4.0 许可协议

>>> string="abc&def#ghi"
>>> for ch in ['&','#']:
...   if ch in string:
...      string=string.replace(ch,"\\"+ch)
...
>>> print string
abc\&def\#ghi

原文由 ghostdog74 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题