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

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

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

其他回答

你可以考虑写一个通用的转义函数:

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

通过这种方式,您可以使用应该转义的字符列表使您的函数可配置。

使用正则表达式的高级方式

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)

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

简短而甜蜜,翻译是优越的替代。如果您对随时间变化的功能优化更感兴趣,请不要使用replace。

如果不知道要替换的字符集是否与用于替换的字符集重叠,也可以使用translate。

举个例子:

使用replace时,您会天真地期望代码段为“1234”。替换(“1”,“2”)。替换(“2”、“3”)。替换("3","4")返回"2344",但实际上它将返回"4444"。

翻译似乎执行了OP最初的期望。

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

a = '&#'

to_replace = ['&', '#']

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

print(a)

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

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