我需要替换一些字符如下:&➔\&,#➔\#,…

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

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

当前回答

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

其他回答

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

替换两个字符

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

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

每个函数的计时:

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*和[另一个]thing在一个较长的句子中,用{more}东西替换$):

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表示可读性和速度。

齿顶高

根据评论中的黑客提示,ab和ba之间的一个区别是文本中的if c: check。让我们用另外两种变体来测试它们:

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(带check)在Python 2上有更大的领先 然而,这里最大的教训是Python 3比Python 2快3倍!Python 3中最慢的和Python 2中最快的没有太大区别!

>>> a = '&#'
>>> print a.replace('&', r'\&')
\&#
>>> print a.replace('#', r'\#')
&\#
>>> 

你想要使用一个'raw'字符串(用'r'作为替换字符串的前缀),因为raw字符串不会特别对待反斜杠。

使用在python2.7和python3中可用的reduce。你可以用简洁的python方式替换多个子字符串。

# Lets define a helper method to make it easy to use
def replacer(text, replacements):
    return reduce(
        lambda text, ptuple: text.replace(ptuple[0], ptuple[1]), 
        replacements, text
    )

if __name__ == '__main__':
    uncleaned_str = "abc&def#ghi"
    cleaned_str = replacer(uncleaned_str, [("&","\&"),("#","\#")])
    print(cleaned_str) # "abc\&def\#ghi"

在python2.7中,你不需要导入reduce,但在python3中。你必须从functools模块中导入它。

也许是一个简单的循环字符替换:

a = '&#'

to_replace = ['&', '#']

for char in to_replace:
    a = a.replace(char, "\\"+char)

print(a)

>>> \&\#