使用Python替换多个字符

pro*_*eek 158 python string replace

我需要更换一些字符如下:&- > \&,#- > \#,...

我编码如下,但我想应该有更好的方法.任何提示?

strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
Run Code Online (Sandbox Code Playgroud)

Hug*_*ugo 352

替换两个字符

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

使用输入字符串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'\#')
Run Code Online (Sandbox Code Playgroud)

时间如下:

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')"
Run Code Online (Sandbox Code Playgroud)

替换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'\$')
Run Code Online (Sandbox Code Playgroud)

这是相同输入字符串的结果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)
Run Code Online (Sandbox Code Playgroud)

输入时间较短:

  • 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用于可读性和速度.

附录

在评论中被haccks提示,ab和之间的区别baif 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)
Run Code Online (Sandbox Code Playgroud)

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          ?
???????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

我们可以得出结论:

  • 支票的人比没有支票的人快4倍

  • ab_with_check在Python 3上稍微领先,但是ba(带有check)在Python 2上有更大的领先优势

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

  • 为什么这不是例外答案? (4认同)
  • @hackks 谢谢,我已经用更多的时间更新了我的答案:添加检查对两者都更好,但最大的教训是 Python 3 的速度提高了 3 倍! (2认同)

gho*_*g74 72

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

  • 双反斜杠转义反斜杠,否则python会将"\"解释为仍然打开的字符串中的文字引号字符. (3认同)
  • 您真的需要if吗?它看起来像是替换操作的重复。 (2认同)

the*_*eye 30

只需链接这样的replace功能

strs = "abc&def#ghi"
print strs.replace('&', '\&').replace('#', '\#')
# abc\&def\#ghi
Run Code Online (Sandbox Code Playgroud)

如果替换的数量更多,您可以通过这种方式执行此操作

strs, replacements = "abc&def#ghi", {"&": "\&", "#": "\#"}
print "".join([replacements.get(c, c) for c in strs])
# abc\&def\#ghi
Run Code Online (Sandbox Code Playgroud)


tom*_*sen 20

这是一个使用str.translate和的python3方法str.maketrans:

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

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

  • 此方法允许执行链接版本无法执行的“破坏替换”。例如,将“a”替换为“b”,将“b”替换为“a”。 (5认同)
  • 这是一个很好的答案,但在实践中执行一个 `.translate()` 似乎比三个链接的 `.replace()`(使用 CPython 3.6.4)慢。 (2认同)

ken*_*ytm 15

你总是会在前面加上反斜杠吗?如果是这样,试试吧

import re
rx = re.compile('([&#])')
#                  ^^ fill in the characters here.
strs = rx.sub('\\\\\\1', strs)
Run Code Online (Sandbox Code Playgroud)

它可能不是最有效的方法,但我认为这是最简单的方法.

  • aarrgghh试试'r'\\\ 1'` (14认同)

krm*_*krm 10

对于Python 3.8及以上版本,可以使用赋值表达式

[text := text.replace(s, f"\\{s}") for s in "&#" if s in text];
Run Code Online (Sandbox Code Playgroud)

虽然,我很不确定这是否被认为是PEP 572中描述的赋值表达式的“适当使用” ,但看起来很干净并且读起来很好(在我看来)。如果您在 REPL 中运行此命令,则末尾的分号会抑制输出。

如果您还想要所有中间字符串,这将是“合适的”。例如,(删除所有小写元音):

text = "Lorem ipsum dolor sit amet"
intermediates = [text := text.replace(i, "") for i in "aeiou" if i in text]

['Lorem ipsum dolor sit met',
 'Lorm ipsum dolor sit mt',
 'Lorm psum dolor st mt',
 'Lrm psum dlr st mt',
 'Lrm psm dlr st mt']
Run Code Online (Sandbox Code Playgroud)

从好的方面来说,它似乎(出乎意料地?)比接受的答案中的一些更快的方法更快,并且似乎随着字符串长度的增加和替换数量的增加而表现良好。

比较

上述比较的代码如下。我使用随机字符串来让我的生活变得更简单,并且要替换的字符是从字符串本身中随机选择的。(注意:我在这里使用 ipython 的 %timeit 魔法,所以在 ipython/jupyter 中运行它)。

import random, string

def make_txt(length):
    "makes a random string of a given length"
    return "".join(random.choices(string.printable, k=length))

def get_substring(s, num):
    "gets a substring"
    return "".join(random.choices(s, k=num))

def a(text, replace): # one of the better performing approaches from the accepted answer
    for i in replace:
        if i in text:
             text = text.replace(i, "")

def b(text, replace):
    _ = (text := text.replace(i, "") for i in replace if i in text) 


def compare(strlen, replace_length):
    "use ipython / jupyter for the %timeit functionality"

    times_a, times_b = [], []

    for i in range(*strlen):
        el = make_txt(i)
        et = get_substring(el, replace_length)

        res_a = %timeit -n 1000 -o a(el, et) # ipython magic

        el = make_txt(i)
        et = get_substring(el, replace_length)
        
        res_b = %timeit -n 1000 -o b(el, et) # ipython magic

        times_a.append(res_a.average * 1e6)
        times_b.append(res_b.average * 1e6)
        
    return times_a, times_b

#----run
t2 = compare((2*2, 1000, 50), 2)
t10 = compare((2*10, 1000, 50), 10)
Run Code Online (Sandbox Code Playgroud)


Vic*_*lex 6

您可以考虑编写一个通用转义函数:

def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])

>>> esc = mk_esc('&#')
>>> print esc('Learn & be #1')
Learn \& be \#1
Run Code Online (Sandbox Code Playgroud)

这样,您可以使用应该转义的字符列表配置您的功能.


Seb*_*nso 5

晚会晚了,但是我在这个问题上浪费了很多时间,直到找到答案。

简短而甜美,translate优于replace。如果您对随时间推移进行的功能优化更感兴趣,请不要使用replace

还可以使用translate,如果你不知道,如果重叠设置的用于替换的字符将被替换的字符集。

例子:

使用replace您会天真地希望代码片段"1234".replace("1", "2").replace("2", "3").replace("3", "4")返回"2344",但是实际上它会返回"4444"

翻译似乎可以执行OP最初想要的功能。