Replace words in a String using a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 17, 2022

banner

Photo from Unsplash

Replace words in a String using a Dictionary in Python #

To replace words in a string using a dictionary:

  1. Use a for loop to iterate over the dictionary's items.
  2. Use the str.replace() method to replace words in the string with the dictionary's items.
  3. The str.replace() method will return a new string with the matches replaced.
main.py
my_str = 'site | name' my_dict = { 'site': 'bobbyhadz.com', 'name': 'borislav' } for key, value in my_dict.items(): my_str = my_str.replace(key, value) # 👇️ bobbyhadz.com | borislav print(my_str)

We used a for loop to iterate over the dictionary's items.

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = { 'site': 'bobbyhadz.com', 'name': 'borislav' } # 👇️ dict_items([('site', 'bobbyhadz.com'), ('name', 'borislav')]) print(my_dict.items())

On each iteration, we use the str.replace() method to replace substrings in the string with values from the dictionary.

main.py
my_str = 'site | name' my_dict = { 'site': 'bobbyhadz.com', 'name': 'borislav' } for key, value in my_dict.items(): my_str = my_str.replace(key, value) # 👇️ bobbyhadz.com | borislav print(my_str)

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

Use the str.lower() method if you need to convert the dictionary's keys and values to lowercase.

main.py
my_str = 'site | name' my_dict = { 'SITE': 'BOBBYHADZ.COM', 'NAME': 'BORISLAV' } for key, value in my_dict.items(): my_str = my_str.replace(key.lower(), value.lower()) # 👇️ bobbyhadz.com | borislav print(my_str)

The str.lower method returns a copy of the string with all the cased characters converted to lowercase.

You can also use the re.sub() method to replace words in the strings using the dictionary's items in a case-insensitive manner.

main.py
import re my_str = 'site | name' my_dict = { 'SITE': 'BOBBYHADZ.COM', 'NAME': 'BORISLAV' } for key, value in my_dict.items(): my_str = re.sub(key, value.lower(), my_str, flags=re.IGNORECASE) # 👇️ bobbyhadz.com | borislav print(my_str)

The re.sub method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

Notice that we set the re.IGNORECASE flag to ignore the case when matching words in the string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.