In this article, we will discuss how to replace multiple words in a string based on a dictionary.
Table of Contents
Suppose we have a string,
"This is the last rain of Season and Jack is here."
We want to replace multiple words in this string using a dictionary i.e.
{'is' : 'AA', 'the': 'BBB', 'and': 'CCC'}
Keys in the dictionary are the substrings that need to be replaced, and the corresponding values in the dictionary are the replacement strings. Like, in this case,
- “is” should be replaced by “AA”
- “the” should be replaced by “BBB”
- “and” should be replaced by “CCC”
The final string should be like,
ThAA AA BBB last rain of Season CCC Jack AA here.
There are different ways to do this. Let’s discuss them one by one.
Using str.replace() function
The string class has a member function replace(to_be_replaced, replacement) and it replaces all the occurrences of substring “to_be_replaced” with “replacement” string.
To replace all the multiple words in a string based on a dictionary. We can iterate over all the key-value pairs in a dictionary and, for each pair, replace all the occurrences of “key” substring with “value” substring in the original string.
For example:
strValue = "This is the last rain of Season and Jack is here." # Dictionary containing mapping of # values to be replaced and replacement values dictOfStrings = {'is' : 'AA', 'the': 'BBB', 'and': 'CCC'} # Iterate over all key-value pairs in dict and # replace each key by the value in the string for word, replacement in dictOfStrings.items(): strValue = strValue.replace(word, replacement) print(strValue)
Output:
ThAA AA BBB last rain of Season CCC Jack AA here.
It replaced all the dictionary keys/words in a string with the corresponding values from the dictionary.
Using Regex
In Python, the regex module provides a function sub(pattern, replacement_str, original_str) to replace the contents of a string based on a matching regex pattern.
This function returns a modified copy of given string “original_str” after replacing all the substrings that matches the given regex “pattern” with a substring “replacement_str”.
To replace all the multiple substrings in a string based on a dictionary. We can loop over all the key-value pairs in a dictionary and for each key-value pair, replace all the occurrences of “key” substring with “value” substring in the original string using the regex.sub() function.
For example:
import re strValue = "This is the last rain of Season and Jack is here." # Dictionary containing mapping of # values to be replaced and replacement values dictOfStrings = {'is' : 'AA', 'the': 'BBB', 'and': 'CCC'} # Iterate over all key-value pairs in dict and # replace each key by the value in the string for word, replacement in dictOfStrings.items(): strValue = re.sub(word, replacement, strValue) print(strValue)
Output:
ThAA AA BBB last rain of Season CCC Jack AA here.
It replaced all the dictionary keys/words in a string with the corresponding values from the dictionary.
Summary:
We learned to replace multiple words in a string based on a dictionary in Python.
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.