Python String Replace: Explained with 2 Examples

Python String Replace: Explained with 2 Examples

What is string replace method in Python?

The Python replace method of String replaces a substring in a given string to the word given in the replace method. The original string remains the same as such strings are immutable in Python.

An example of replace method

Syntax of string replace method

Following is the general syntax of the replace method:

String.replace(existing_substring,to_be_replaced_with[(, max])

Where existing substring is the word or characters in the given string followed by to be replaced with text. The max (optional) parameter specifies how many times the replace method should replace the given substring.

For example, if the ‘is’ word is occurring 5 times in a string and you want to replace it with the “was”, by default, it will replace all 5 occurrences. If you want to restrict it to three replacements then the max parameter can be used. In that case, only the first three occurrences will be replaced. This is shown in the second example below.

String replace method example

In the following example, we will replace the word “this” with “that” in a given string which is followed by displaying the whole string before and after using the replace Python method.

As such strings are not changeable, we will print the original string variable to show that it remains unchanged.

Python string replace

See this example online

The output will be:

String before replace method: This is Python strings lesson. This explains strings and string’s methods

String after replace method: That is Python strings lesson. That explains strings and string’s methods

##############################################

Original string: This is Python strings lesson. This explains strings and string’s methods

Using max parameter in Python replace method

Using above example with the max parameter in string replace method, only one replacement of “this” to “that” will occur.

See this example online

The output will be:

String before python replace method: This is string replace lesson. This explains strings and string’s methods

String after replace method: That is Python strings lesson. This explains strings and string’s methods

You can see, only the first occurrence of the word “This” is changed to “That”.

 

Further reading: String length method | Python split