Python replace word in string

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

"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.

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,

Frequently Asked:

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 = # 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)
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.

Читайте также:  Python tkinter полный экран

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 = # 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)
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.

We learned to replace multiple words in a string based on a dictionary in Python.

Источник

Python String replace() Method

The replace() method replaces a specified phrase with another specified phrase.

Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

Syntax

Parameter Values

Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences
Читайте также:  Самоучитель по си шарп

More Examples

Example

Replace all occurrence of the word «one»:

txt = «one one was a race horse, two two was one too.»

Example

Replace the two first occurrence of the word «one»:

txt = «one one was a race horse, two two was one too.»

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python String replace() Method

The Python String replace() method replaces all occurrences of one substring in a string with another substring. This method is used to create another string by replacing some parts of the original string, whose gist might remain unmodified.

For example, in real-time applications, this method can be used to replace multiple same spelling mistakes in a document at a time.

This replace() method can also replace selected number of occurrences of substrings in a string instead of replacing them all.

Syntax

Following is the syntax for Python String replace() method −

Parameters

  • old − This is old substring to be replaced.
  • new − This is new substring, which would replace old substring.
  • count − If this optional argument count is given, only the first count occurrences are replaced.

Return Value

This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Читайте также:  Read xml file with python

Example

The following example shows the usage of Python String replace() method.

str = "Welcome to Tutorialspoint" str_replace = str.replace("o", "0") print("String after replacing: " + str_replace)

When we run above program, it produces following result −

String after replacing: Welc0me t0 Tut0rialsp0int

Example

When we pass the substring parameters along with the optional count parameter, the method only replaces the first count occurrences in the string.

In this example below, the input string is created and the method takes three arguments: two substrings and one count value. The return value will be the string obtained after replacing the first count number of occurrences.

str = "Fred fed Ted bread and Ted fed Fred bread." strreplace = str.replace("Ted", "xx", 1) print("String after replacing: " + strreplace)

When we run above program, it produces following result −

String after replacing: Fred fed xx bread and Ted fed Fred bread.

Example

When we pass two substrings and count = 0 as parameters to the method, the original string is returned as the result.

In the following example, we created a string «Learn Python from Tutorialspoint» and tried to replace the word «Python» with «Java» using the replace() method. But, since we have passed the count as 0, this method does not modify the current string, instead of that, it returns the original value («Learn Python from Tutorialspoint»).

str = "Learn Python from Tutorialspoint" strreplace = str.replace("Python", "Java", 0) print("String after replacing: " + strreplace)

If you execute the program above, the outpit is displayed as −

String after replacing: Learn Python from Tutorialspoint

Источник

Оцените статью