如何使用python3查找多个字符并替换多个字符?
string = "us/i5/v"
l=[]
for i in string:
if i == "u" :
i = i.replace("u","w")
l.append(i)
if i == "s" :
i = i.replace("s","5")
l.append(i)
if i == "i" :
i = i.replace("i","1")
l.append(i)
print(l)
预期输出:
w5/15/v
答案 0 :(得分:3)
translation_table = str.maketrans({'u': 'w', 's': '5', 'i':'1'})
string = "us/i5/v"
print(string.translate(translation_table))
# w5/15/v
请注意,如果稍后替换其中一个替换项,则像replace
这样重复使用string.replace("u","w").replace("s","5")...
可能会导致不良结果。例如,如果要将a
替换为b
,将b
替换为c
,
'ab'.replace('a', 'b').replace('b', 'c') # Don't !
将提供'cc'
,而不是'bc'
。
因此,除非您确定不会遇到此类问题,否则使用str.translate
是更好的解决方案。
答案 1 :(得分:1)
如果有很多映射,请使用字典。
string = "us/i5/v"
d = {
"u": "w",
"s": "5",
"i": "1"
}
new_string = "".join([d.get(e, e) for e in string])
答案 2 :(得分:0)
replace()
适用于字符串而不适用于字符,也可以按以下顺序应用。您还可以使用list()
将输出显示为列表:
string = "us/i5/v"
string = string.replace("u","w").replace("s","5").replace("i","1")
l = list(string)
print(string)
print(l)
答案 3 :(得分:0)
如注释中所述,.replace(before, after)
函数处理字符串,而不仅仅是单个字符。您也可以将它们链接在一起。以您的示例为基础
transform_pairs = [
('u', w'),
('s', '5'),
('i', '1'),
# more rules as you need
]
string = 'us/i5/v'
for old, new in transform_pairs:
string = string.replace(old, new)
string == 'w5/15/v'
答案 4 :(得分:0)
使用元组拆包:
s = "us/i5/v"
# list of all the chars to replace along with their replacement
replaceList = [("u", "w"), ("s", "5"), ("i", "1")]
for elem in replaceList:
s = s.replace(*elem)
print(s)
输出:
w5/15/v