当我使用字典替换字符串中的值以解码消息时,如何将其放入以便函数不将替换值读取为键并再次替换替换值? / p>
def decipher_message(translation_guide, message):
t = read_translation_guide_into_dictionary(translation_guide)
e = read_message(message)
print(t)
print(e)
for key, value in t.items():
f = e
e = f.replace(key, value)
return e
输出:
{'a':'m','b':'a','c':'c','d':'y','e':'t','f':'v ', '走', 'h':'u','i':'x','j':'e','k':'j','l':'w','m':'f','n ':'z', 'o':'d','p':'l','q':'i','r':'k','s':'h','t':'n','u ': 'G', 'v':'b','w':'q','x':'s','y':'p','z':'r'}
“ qa mqtbppd vjqtu mghto!esbtr dgh mgz mqtoqtu aj gs rqto xezbtujz。q ahxe ejpp dgh,qex whqej vgzqtu sbfqtu bpp esj ljbpes qt esj lgzpo。质量 dghzj pggrqtu mgz qe,q vhzqjo b aby eg qe bzghto lsjzj dghzj xebtoqtu tgl! zjajavjz esghus:ljbpes qxte jfjzdesqtu qt esj lgzpo!“
'“”如果finallp被fdgnd!nhank pdg fdr找到fe dh类的连击者。 fgsn nell pdg,ins qgine bdring在ndr qdrld中添加了所有qealnh。如果 pdgre lddking fdr in,我在ardgnd qhere bfd nd fap nd ndq! refefber nhdggh:qealnh isnn eberpnhing in nhe qdrld!“'
答案 0 :(得分:5)
您应该遍历字符串并将每个字符替换为字典中的值,而不是遍历字典并对整个字符串进行替换:
decoded = []
for letter in e:
decoded.append(t.get(letter, letter))
return ''.join(decoded)
还请注意,Python有一个内置的字符串转换方法,该方法带有一个可从您的字典生成的表:
table = str.maketrans(t)
return e.translate(table)
答案 1 :(得分:3)
您可以将str.join
与以下生成器表达式一起使用,该表达式遍历字符串以转换每个字符:
def decipher(translation, message):
t = read_translation(translation)
e = read_message(message)
return ''.join(t.get(c, c) for c in e)