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

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

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

当前回答

下面给出了or条件的例子,它将删除给定字符串中的所有'和'。传递任意数量的字符,以|分隔

import re
test = re.sub("('|,)","",str(jsonAtrList))

之前:

后:

其他回答

这将帮助人们找到一个简单的解决方案。

def replacemany(our_str, to_be_replaced:tuple, replace_with:str):
    for nextchar in to_be_replaced:
        our_str = our_str.replace(nextchar, replace_with)
    return our_str

os = 'the rain in spain falls mainly on the plain ttttttttt sssssssssss nnnnnnnnnn'
tbr = ('a','t','s','n')
rw = ''

print(replacemany(os,tbr,rw))

输出:

他是我的家人他的pli

你总是要在反斜杠前加引号吗?如果是,试试

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

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

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

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

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

举个例子:

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

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

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

像这样简单地连接替换函数

strs = "abc&def#ghi"
print strs.replace('&', '\&').replace('#', '\#')
# abc\&def\#ghi

如果替换的数量更多,你可以用这种通用的方法

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