1

I'm trying to map one letter to another in Python 3. But I'm getting the wrong output. Here's one of the test inputs:

txt = 'wlgp le scd wlgp'

output should be:

pick is the pick

But I'm getting this wrong output:

pick it tht pick

Here's my code:

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)
  • 1
    You get the wrong output because you keep on replacing values in the same string. E.g. `d` becomes `s`, and then `s` becomes `n` in a later replacement. Better approaches suggested [here](https://stackoverflow.com/questions/555705/character-translation-using-python-like-the-tr-command). – Robby Cornelissen Apr 05 '22 at 03:49

1 Answers1

1

If you are a fresher, you can do my easy way is getting each character in the string, check it in your mapping1 or not and return a suitable value, put it into a list, and use join to join the array by ''. I hope helpful to you

string = "".join([mapping1.get(c) if c in mapping1 else c for c in string])