我試圖在 Python 3 中將一個字母映射到另一個字母。但我得到了錯誤的輸出。這是測驗輸入之一:
txt = 'wlgp le scd wlgp'
輸出應該是:
pick is the pick
但我得到了這個錯誤的輸出:
pick it tht pick
這是我的代碼:
def swapCharacters(txt):
hash = {'c':'h', 'd':'e', 'e':'s', 'g':'c', 'l':'i', 'p':'k', 's':'t', 'w':'p'}
for key in hash.keys():
txt = txt.replace(key, hash[key])
print(txt)
uj5u.com熱心網友回復:
如果你是一個新手,你可以做我的簡單方法是獲取字串中的每個字符,檢查它是否輸入mapping1并回傳一個合適的值,將它放入一個串列中,并使用join''加入陣列。希望對你有幫助
string = "".join([mapping1.get(c) if c in mapping1 else c for c in string])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456003.html
標籤:python-3.x 字典 映射
上一篇:如何添加資料框字典的列?
