OneBite.Dev - Coding blog in a bite size

replace multiple words in a string in python

Code snippet on how to replace multiple words in a string in python

  def multiple_replace(text, word_dic):
      for key in word_dic:
          text = text.replace(key, word_dic[key])
      return text

This code allows you to replace multiple words in a string. The function takes two arguments, the text and a dictionary which contains the words you want to replace and the words you want to replace them with.

First, we use a loop to iterate through each keyword in the dictionary. Then, we use the .replace method to replace each keyword with the corresponding value from our dictionary. The .replace method takes two arguments, the word you’re trying to replace, and the word you want to replace it with. Finally, we return the modified string.

python