fo=open("sample.txt","r")
item=fo.readlines()
fo.close()
replacements = (('4','A'),('8','b'),('3','e'),('5','s'),('7','t'),('@','a'),('3','e'),('0','o'))
new_string = item
for new, old in replacements:
new_string = new_string.replace(new, old)
print ( new_string)
我编写了以下代码,但没有阅读我的列表。我的目标是翻译清单。
答案 0 :(得分:0)
使用str.translate()
使用翻译表以加快翻译速度。这是一个例子:
with open("sample.txt","r") as fo:
lines = fo.readlines()
replacements = {'4':'A', '8':'b', '3':'e', '5':'s', '7':'t', '@':'a', '3':'e', '0':'o'}
trans_table = str.maketrans(replacements)
for line in lines:
print(line, end="")
new_line = line.translate(trans_table)
print(new_line)
输出:
h3llo 70 y0u
hello to you
4 8377er w0rld 70d@y
A better world today