我需要替换一些字符如下:&➔\&,#➔\#,…
我的编码如下,但我想应该有更好的方法。有提示吗?
strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
我需要替换一些字符如下:&➔\&,#➔\#,…
我的编码如下,但我想应该有更好的方法。有提示吗?
strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
当前回答
下面是使用str.translate和str.maketrans的python3方法:
s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))
打印出来的字符串是abc\&def\#ghi。
其他回答
>>> a = '&#'
>>> print a.replace('&', r'\&')
\&#
>>> print a.replace('#', r'\#')
&\#
>>>
你想要使用一个'raw'字符串(用'r'作为替换字符串的前缀),因为raw字符串不会特别对待反斜杠。
使用在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模块中导入它。
这个怎么样?
def replace_all(dict, str):
for key in dict:
str = str.replace(key, dict[key])
return str
then
print(replace_all({"&":"\&", "#":"\#"}, "&#"))
输出
\&\#
类似的答案
使用正则表达式的高级方式
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 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