65

Replace words in a string using dictionary in Python

 2 years ago
source link: https://thispointer.com/replace-words-in-a-string-using-dictionary-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Replace words in a string using dictionary in Python

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."
"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'}
{'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,

Advertisements

vid5e6258f9da92c874459691.jpg?cbuster=1600267117
liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2ZW50PTUjJaNypaZypyRcoWU9MTY1MTU5NDY2OCZ2nWRspGkurWVlVzVlPTMhMS4jJaM9MTAkMwx3JaN0YT0jJat9NDUmJax9MmI1JaZcZF9jYXNmRG9gYWyhPXRbnXNjo2yhqGVlLzNioSZmqWJJZD10nGympG9coaRypv5wo20zZGVvqWqJozZipz1uqGyiow0znXNBpHA9MCZlnT02QmY5NmY2NTUmNmQ2MTp0NmM3QmpmNxImMTqCNTQmMDqEN0I2NDMlMmAmMwMlMxQmMDM1MxQmMDMmNUYmMTM5N0Q3QwpmMmEmMwMmMmQmOTM2MmQmOTqEN0I0MmMkMmpmMwqEN0I1MmY0NDp2ODpjNwMmMmQlNmY2MTU3MmUmMDVBNTt0OTp1NTxmMwM5NmQ3RDqCNwI2MmY4NmI2RwZENwU3RDqCNmE2NDY1NmM2Qwp0NxY3MDqEN0I2RwZDNwx2RTp1Nmt3RDqCNTtmNDM1MmM3RDqCNTxmMmMlMmU3RDqCNwYmMTqEN0I0QmMkMmImNTMlMmE3REZFRxUzZGyunWQ9JaVmZXJJpEFxZHI9MTQkLwE2NC42Ml4kNwQzqXNypyVBPU1irzyfoGEyMxY1LwAyMwAyMwuYMTEyM0IyMwBMnW51rCUlMHt4Ny82NCUlOSUlMEFjpGkyV2VvS2y0JTJGNTM3LwM2JTIjJTI4S0uUTUjyMxMyMwBfnWgyJTIjR2Vwn28yMwxyMwBDnHJioWUyMxY3Nl4jLwM4NwUhMTIjJTIjU2FzYXJcJTJGNTM3LwM2JzNmqXVcZD02MwpkNTVuYwY5MDYlJzNioaRyoaRGnWkySWQ9MCZgZWRcYVBfYXyMnXN0SWQ9MCZgZWRcYUkcp3RJZD0jJzqxpHI9MCZaZHBlQ29hp2VhqD0znXNXZVBup3NHZHBlPTEzY2NjYT0jJzNwpGFDo25mZW50PSZwYaVmqGVlPTE2NTE1OTQ2NmAjNmMzqWyxPVNyn2yhZG9TUGkurWVlNwI3MTU1YWNxMGFzMCZjqWJVpzj9nHR0pHMyM0EyMxYyMxZ0nGympG9coaRypv5wo20yMxZlZXBfYWNyLXqipzRmLWyhLWEgp3RlnW5aLXVmnW5aLWRcY3Rco25upaxgnW4gpHy0nG9hJTJGJzZfo2F0U3RuqHVmPWZuoHNyJzVcZHNjPXBlZWJcZA==
  • “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.
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)
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.
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)
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.
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

 

 

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.

Join a LinkedIn Community of Python Developers

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK