Last updated: Apr 9, 2024
Reading timeยท3 min
To replace words in a string using a dictionary:
for
loop to iterate over the dictionary's items.str.replace()
method to replace words in the string with the
dictionary's items.str.replace()
method will return a new string with the matches
replaced.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).
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.
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:
Name | Description |
---|---|
old | The substring we want to replace in the string |
new | The replacement for each occurrence of old |
count | Only 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.
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.
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've also written an article on how to replace values in a dictionary.
You can learn more about the related topics by checking out the following tutorials: