Anayatc Anayatc - 3 months ago 15
Python Question

replace multiple characters in string with value from dictionary python

I'm trying to create a function that iterates through a string, finds characters that match to keys in a dictionary and replaces that character with the value in the dictionary for that key. However it currently only replaces first occurrence of a letter that is in the dictionary and stops there, where am I going wrong?

d = {
'I':'1', 'R':'2', 'E':'3', 'A':'4', 'S':'5', 'G':'6', 'T':'7', 'B':'8', 'O':'0',
'l':'1', 'z':'2', 'e':'3', 'a':'4', 's':'5', 'b':'6', 't':'7', 'g':'9', 'o':'0',
}

def cypher(string):
for i in string:
if i in d:
a = string.replace(i,d[i])
return a

Answer

You are prematurely ending your code with the call to return within the for loop. You can fix it by storing your new string outside of the loop, only returning once the loop is done:

def cypher(string):
    a = string  # a new string to store the replaced string
    for i in string:
        if i in d:
            a = a.replace(i, d[i])
    return a

There is something wrong about the logic too, though. If you have a value in your dictionary that is also a key in the dictionary, the key may get replaced twice. For example, if you have d = {'I': 'i', 'i': 'a'}, and the input is Ii, your output would be aa.

Here's a much more concise implementation using join that does not have this problem.

def cypher(string):
    return ''.join(d.get(l, l) for l in string)