替换字符串中多个字符的最佳方法?
我需要替换一些字符如下: &
➔ \&
, #
➔ \#
, ...
I need to replace some characters as follows: &
➔ \&
, #
➔ \#
, ...
我编码如下,但我想应该有更好的方法.有什么提示吗?
I coded as follows, but I guess there should be some better way. Any hints?
strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
替换两个字符
我对当前答案中的所有方法以及一个额外方法进行了计时.
Replacing two characters
I timed all the methods in the current answers along with one extra.
使用 abc&def#ghi
的输入字符串并替换 &-> \&和# -> \#,最快的方法是像这样将替换链接在一起: text.replace('&', '\&').replace('#', '\#')代码>.
With an input string of abc&def#ghi
and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: 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 个字符
这里有类似的代码来做同样的事情,但有更多的字符要转义 (\`*_{}>#+-.!$):
Replacing 17 characters
Here's similar code to do the same but with more characters to escape (\`*_{}>#+-.!$):
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
:
Here's the results for the same input string 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* 和 [another] 东西在一个更长的句子中,用 {more} 个东西替换 $
):
And with a longer input string (## *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
来提高可读性和速度.
So I'm going to use ba
for readability and speed.
在评论中的 hack 提示下,ab
和 ba
之间的一个区别是 if c in text:
检查.让我们针对另外两个变体来测试它们:
Prompted by haccks in the comments, one difference between ab
and ba
is the if c in text:
check. Let's test them against two more variants:
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 为单位,因此无法直接比较.
Times in μs per loop on Python 2.7.14 and 3.6.3, and on a different machine from the earlier set, so cannot be compared directly.
╭────────────╥──────┬───────────────┬──────┬──────────────────╮
│ 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 倍
Those with the check are up to 4x faster than those without the check
ab_with_check
在 Python 3 上略微领先,但 ba
(带检查)在 Python 2 上有更大的领先
ab_with_check
is slightly in the lead on Python 3, but ba
(with check) has a greater lead on Python 2
然而,这里最大的教训是Python 3 比 Python 2 快 3 倍!Python 3 上最慢的和 Python 2 上最快的并没有太大区别!
However, the biggest lesson here is Python 3 is up to 3x faster than Python 2! There's not a huge difference between the slowest on Python 3 and fastest on Python 2!