我需要替换一些字符如下:&➔\&,#➔\#,…
我的编码如下,但我想应该有更好的方法。有提示吗?
strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
我需要替换一些字符如下:&➔\&,#➔\#,…
我的编码如下,但我想应该有更好的方法。有提示吗?
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
其他回答
使用正则表达式的高级方式
import re
text = "hello ,world!"
replaces = {"hello": "hi", "world":" 2020", "!":"."}
regex = re.sub("|".join(replaces.keys()), lambda match: replaces[match.string[match.start():match.end()]], text)
print(regex)
你可以考虑写一个通用的转义函数:
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
通过这种方式,您可以使用应该转义的字符列表使您的函数可配置。
下面是使用str.translate和str.maketrans的python3方法:
s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))
打印出来的字符串是abc\&def\#ghi。
对于Python 3.8及以上版本,可以使用赋值表达式
[text := text.replace(s, f"\\{s}") for s in "&#" if s in text];
虽然,我不确定这是否被认为是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']
从好的方面来看,它似乎(出乎意料地?)比公认答案中的一些更快的方法要快,并且似乎在增加字符串长度和增加替换次数的情况下都表现得很好。
下面是用于上述比较的代码。我使用随机字符串来简化我的工作,要替换的字符是从字符串本身随机选择的。(注意:我在这里使用的是ipython的%timeit magic,所以在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)
这个怎么样?
def replace_all(dict, str):
for key in dict:
str = str.replace(key, dict[key])
return str
then
print(replace_all({"&":"\&", "#":"\#"}, "&#"))
输出
\&\#
类似的答案