gpt4 book ai didi

python - 从列表中取出字符并将它们变成其他字符

转载 作者:行者123 更新时间:2023-11-28 18:27:26 26 4
gpt4 key购买 nike

我已经制作了一种 secret 语言,我可以将完整的单词放入输入中并获得列表中字母应该是的输出。比方说,我输入“AB”,我希望输出为“QW”。

while True:
print("type sentence you want translated")
Befor=input()
After=list(Befor)

if Befor=="A":
print("Q")
elif Befor=="B":
print("W")
elif Befor=="C":
print("E")
elif Befor=="D":
print("R")
else:
print("--")

print(After)

pass

最佳答案

您正在输入两个字母,但您的测试条件每个只包含一个字符。您应该使用 for 迭代输入字符串并一次测试字符串中的每个字符:

before = input()

for i in before:
if i=="A":
print("Q")
elif i=="B":
print("W")
elif i=="C":
print("E")
elif i=="D":
print("R")
else:
print("--")

您还可以通过使用映射 代替if/elif 来改进您的代码,因为这将帮助您更轻松地适应新的翻译:

before = input()
mapping = {'A': 'Q', 'B': 'W', 'C': 'E', 'D': 'R'}

after = ''.join(mapping.get(x, '--') for x in before)
print(after)

注意当映射不包含字符时,字典的 get 方法是如何返回默认的 '--' 的。

关于python - 从列表中取出字符并将它们变成其他字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40330896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com