How do I map one letter to another in Python?

Viewed 85

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 Answers

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])
Related