Simone Jones Simone Jones - 1 month ago 8
Python Question

Taking characters out of list and turning them into other characters

I have made a Secret language that i would to be able to put full words into the input and get the output as the list says the letters should be. Lets say for example I input "AB" I would like the out put to be "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

Answer

You're inputting two letters, but your test conditions only contain one character each. You should iterate on the input string using a for and test each character in the string one at a time:

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("--")

You can also improve your code by using a mapping instead of the if/elif as this will help you accommodate new translations more easily:

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

after = ''
for i in before:
    after += mapping.get(i, '--') 

print(after)

Notice how the dictionary's get method was used to return the default '--' when the mapping does not contain the character.