Search code examples
pythonsymbols

Why symbols are not appending in order?


string_to_translate: dict ={
"a":"@",
"b":"6",
"c":"¢",
"d":"p",
"e":"€",
"f":"√",
}

while True:
    sentence_to_translate: str = str(input("Wpisz zdanie: "))
    sentence_after_formatting: list = [char for char in sentence_to_translate]
    translated_sentence: list = []
    for y in string_to_translate.keys():
        for x in sentence_after_formatting:
            if y == x:
                translated_sentence.append(translated_sentence[y])
            
    print(translated_sentence)
    break

When I type, for example, "fed", I'm getting ['p', '€', '√'], where it should be ['√', '€', 'p'].

Why is this happening? Thanks for help


Solution

  • You're very close to the ideal answer if you wish to translate keys in the dictionary to their corresponding values. Your confusingly named dictionary gets you 99% of the way there. You just need to use str.maketrans and str.translate.

    >>> string_to_translate: dict ={
    ... "a":"@",
    ... "b":"6",
    ... "c":"¢",
    ... "d":"p",
    ... "e":"€",
    ... "f":"√",
    ... }
    >>> t = str.maketrans(string_to_translate)
    >>> "Hello".translate(t)
    'H€llo'