-1

I am trying to make a code that changes a letter to another according to a dictionary. If it finds the letter "o" in a string, it changes to "e", for example. The way I came up with technically worked but still adds more elements for some reason and I couldn't figure it out unfortunately. (Python beginner) Here is the code:

dict1 = {"o":"e", "p":"l"}
text = "op"
text2 = ""
for key,value in dict1.items():
    y = text.replace(key,value)
    text2 +=y
print(text2)
ModyDz
  • 115
  • 8
  • 1
    `print(y)` on each iteration and see what you have. – Thierry Lathuille Mar 06 '21 at 18:18
  • See [Best way to replace multiple characters in a string?](https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string) – ggorlen Mar 06 '21 at 18:25
  • 1
    CaptainTrojan's answer addresses your direct problem. For a more general solution, see for example https://stackoverflow.com/questions/13626728/replacing-characters-in-a-string-using-dictionary-in-python – Thierry Lathuille Mar 06 '21 at 18:27

1 Answers1

0

You're performing key-wise updates and appending them to an empty string. Just use

dict1 = {"o":"e", "p":"l"}
text = "op"
for key,value in dict1.items():
    text = text.replace(key,value)
print(text)

Your values of y and text2:

  1. y='ep' -> text2 = '' + 'ep' = 'ep'
  2. y='ol' -> text2 = 'ep' + 'ol' = 'epol'
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28
  • This will not work in a more general case, though, where some replacements might be replaced again later. – Thierry Lathuille Mar 06 '21 at 18:21
  • @ThierryLathuille It is the smallest update to OP's code. If they wanted to fix their algorithm logic, I would iterate over text characters and not the update characters for the whole text at once, but hey. – Captain Trojan Mar 06 '21 at 18:22