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

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

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

当前回答

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

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。

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

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

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

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

举个例子:

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

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

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

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

使用在python2.7和python3中可用的reduce。你可以用简洁的python方式替换多个子字符串。

# Lets define a helper method to make it easy to use
def replacer(text, replacements):
    return reduce(
        lambda text, ptuple: text.replace(ptuple[0], ptuple[1]), 
        replacements, text
    )

if __name__ == '__main__':
    uncleaned_str = "abc&def#ghi"
    cleaned_str = replacer(uncleaned_str, [("&","\&"),("#","\#")])
    print(cleaned_str) # "abc\&def\#ghi"

在python2.7中,你不需要导入reduce,但在python3中。你必须从functools模块中导入它。