如何在 Python 中将一个字母映射到另一个字母?
How do I map one letter to another in Python?
我试图在 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)
如果你是新手,你可以按照我的简单方法获取字符串中的每个字符,在你的 mapping1
中检查它是否和 return 一个合适的值,把它放入列表,并使用 join
通过 '' 加入数组。希望对你有所帮助
string = "".join([mapping1.get(c) if c in mapping1 else c for c in string])
我试图在 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)
如果你是新手,你可以按照我的简单方法获取字符串中的每个字符,在你的 mapping1
中检查它是否和 return 一个合适的值,把它放入列表,并使用 join
通过 '' 加入数组。希望对你有所帮助
string = "".join([mapping1.get(c) if c in mapping1 else c for c in string])