从列表中取出字符并将其转换为其他字符

Sim*_*nes 6 python string python-3.x

我已经制作了一种秘密语言,我可以将完整的单词放入输入中并获得输出,因为列表中的字母应该是这样。假设例如我输入“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
Run Code Online (Sandbox Code Playgroud)

Mos*_*oye 7

您正在输入两个字母,但您的测试条件每个只包含一个字符。您应该使用 a 迭代输入字符串并一次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("--")
Run Code Online (Sandbox Code Playgroud)

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

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

after = ''.join(mapping.get(x, '--') for x in before)
print(after)
Run Code Online (Sandbox Code Playgroud)

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