How to Replace Words in Strings with Dictionary Values in Pytho
This guide explains how to replace specific words in a Python string with corresponding values from a dictionary. This is a common task in text processing, template rendering, and data manipulation. We'll cover both case-sensitive and case-insensitive replacements, using straightforward loops and the more powerful re.sub() function for regular expression-based substitutions.
Case-Sensitive Replacement with a for Loop
The most basic approach is to iterate through the dictionary's key-value pairs and use str.replace():
my_str = 'site | name'
my_dict = {
'site': 'tutorialreference.com',
'name': 'tom'
}
for key, value in my_dict.items():
my_str = my_str.replace(key, value)
print(my_str) # Output: tutorialreference.com | tom
my_dict.items(): This method returns a view object that displays a list of a dictionary's key-value tuple pairs.- The
forloop iterates over the dictionary's key-value pairs. my_str.replace(key, value): This replaces all occurrences of thekey(in the string) with the correspondingvalue. Thereplace()method does not modify the original string; it returns a new string with the replacements made. That's why we reassign the result back tomy_str.
This approach performs a case-sensitive replacement. "site" will be replaced, but "Site" or "SITE" will not.
Case-Insensitive Replacement with a for Loop
For case-insensitive replacement using a loop, convert both the key and the string being searched to lowercase (or uppercase) before calling replace():
my_str = 'site | name'
my_dict = {
'SITE': 'TUTORIALREFERENCE.COM',
'NAME': 'TOM'
}
for key, value in my_dict.items():
my_str = my_str.replace(key.lower(), value.lower())
print(my_str) # Output: tutorialreference.com | tom
key.lower()andmy_str.lower(): Convert both to lowercase before comparison. This performs a case-insensitive replacement.
Case-Sensitive Replacement with re.sub()**
You can also use regular expressions with re.sub() method for performing replacements:
import re
my_str = 'site | name'
my_dict = {
'site': 'tutorialreference.com',
'name': 'tom'
}
for key, value in my_dict.items():
my_str = re.sub(key, value, my_str)
print(my_str) # Output: tutorialreference.com | tom
Case-Insensitive Replacement with re.sub()
For more powerful and flexible replacements, especially when dealing with case-insensitivity or word boundaries, use the re.sub() function from the re (regular expression) module:
import re
my_str = 'site | name'
my_dict = {
'SITE': 'TUTORIALREFERENCE.COM',
'NAME': 'TOM'
}
for key, value in my_dict.items():
my_str = re.sub(key, value.lower(), my_str, flags=re.IGNORECASE) #Using re.sub
print(my_str) # Output: tutorialreference.com | tom
re.sub(pattern, repl, string, count=0, flags=0): This function replaces occurrences of apatternin astringwith arepl(replacement).key: The dictionary key (which we'll treat as the "word" to replace).value.lower(): The replacement value (converted to lowercase in the example for consistency)my_str: The string in which we're making replacements.flags=re.IGNORECASE: This makes the search and replace case-insensitive.
- The for loop iterates through the key-value pairs, substituting the values.