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

371 投票
16 回答
810735 浏览
提问于 2025-04-16 02:21

我需要把一些字符替换成这样:& 变成 \&# 变成 \#,等等。

我写了以下代码,但我觉得应该有更好的方法。有什么建议吗?

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

16 个回答

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

87

这里有一个使用 str.translatestr.maketrans 的 Python3 方法:

s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))

打印出来的字符串是 abc\&def\#ghi

741

替换两个字符

我测试了当前答案中的所有方法,还加了一个额外的方法。

在输入字符串为 abc&def#ghi,需要将 & 替换为 \&,# 替换为 \# 的情况下,最快的方式是把替换操作连在一起,像这样:text.replace('&', '\&').replace('#', '\#')

每个函数的执行时间如下:

  • a) 1000000 次循环,最佳为 3 次:每次 1.47 微秒
  • b) 1000000 次循环,最佳为 3 次:每次 1.51 微秒
  • c) 100000 次循环,最佳为 3 次:每次 12.3 微秒
  • d) 100000 次循环,最佳为 3 次:每次 12 微秒
  • e) 100000 次循环,最佳为 3 次:每次 3.27 微秒
  • f) 1000000 次循环,最佳为 3 次:每次 0.817 微秒
  • g) 100000 次循环,最佳为 3 次:每次 3.64 微秒
  • h) 1000000 次循环,最佳为 3 次:每次 0.927 微秒
  • i) 1000000 次循环,最佳为 3 次:每次 0.814 微秒

以下是这些函数的代码:

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 微秒
  • b) 100000 次循环,最佳为 3 次:每次 2.64 微秒
  • c) 100000 次循环,最佳为 3 次:每次 11.9 微秒
  • d) 100000 次循环,最佳为 3 次:每次 4.92 微秒
  • e) 100000 次循环,最佳为 3 次:每次 2.96 微秒
  • f) 100000 次循环,最佳为 3 次:每次 4.29 微秒
  • g) 100000 次循环,最佳为 3 次:每次 4.68 微秒
  • h) 100000 次循环,最佳为 3 次:每次 4.73 微秒
  • i) 100000 次循环,最佳为 3 次:每次 4.24 微秒

对于更长的输入字符串(## *Something* and [another] thing in a longer sentence with {more} things to replace$),结果如下:

  • a) 100000 次循环,最佳为 3 次:每次 7.59 微秒
  • b) 100000 次循环,最佳为 3 次:每次 6.54 微秒
  • c) 100000 次循环,最佳为 3 次:每次 16.9 微秒
  • d) 100000 次循环,最佳为 3 次:每次 7.29 微秒
  • e) 100000 次循环,最佳为 3 次:每次 12.2 微秒
  • f) 100000 次循环,最佳为 3 次:每次 5.38 微秒
  • g) 10000 次循环,最佳为 3 次:每次 21.7 微秒
  • h) 100000 次循环,最佳为 3 次:每次 5.7 微秒
  • i) 100000 次循环,最佳为 3 次:每次 5.13 微秒

增加几个变体:

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 微秒
  • ba) 100000 次循环,最佳为 3 次:每次 2.4 微秒

对于较长的输入:

  • ab) 100000 次循环,最佳为 3 次:每次 7.71 微秒
  • ba) 100000 次循环,最佳为 3 次:每次 6.08 微秒

所以我决定使用 ba,因为它更易读且速度更快。

附录

在评论中受到 haccks 的启发,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 上的每次循环时间(微秒),并且在与之前的测试不同的机器上,所以不能直接比较。

╭────────────╥──────┬───────────────┬──────┬──────────────────╮
│ 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 中最快的差别并不大!

撰写回答