'Replace word by word in a string [closed]

I want to replace a word in a string which is determined by the word entered by the user.

For example, if user enters "pot", the code replaces it with "who" but if he enters "top" then it becomes "mam".

I have a set of 225 words and their replacements. I am using python for this. Replacing each word individually in a condition is really impractical. is their a quicker way to do this. I currently have no code as I am totally confused how to do this.

Using excel throws an error no matter what.



Solution 1:[1]

Yes, there is a very convenient way to do this; python dicts:

d = {"pot": "who", "top": "mam"}
print(d["pot"])
print(d["top"])

Output:

who
mam

In Python 3.1, you can use the new match - case statement:

s = "pot"

match s: 
   case "pot": 
       print("who")
   case "top": 
       print("top")
    case _: 
       print(None)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1