How to replace a substring of a string with specified string in Python

Replacing a substring in Python

In Python, you can replace a substring of a string with specified string using the str.replace() method.



Syntax of str.repalce() method:

Syntax of replacing all matching substrings
Syntax of replacing specified number of substrings

Replacing all matching substrings using 'str.replace()' method

  1. Create a variable named str_variable and assign string value "Python is fun, fun, and fun." to he variable. The string has 3 substrings 'fun'. We will replace all substrings 'fun' with the string 'awesome'.
  2. Apply the replace method (str_variable.replace('fun', 'awesome')) to the string variable str_variable specifying the old substring 'fun' and new string 'awesome'.

    This method will replace all substrings 'fun' of the string with the new string 'awesome'. Assign the result to a new variable called replaced_string and get the output using print() function.

Please take a closer look at the following example:

Example of using str.replace() method

Output of the above example
Example without count: Python is awesome, awesome, and awesome.

Replacing specified number of substrings using 'str.replace()' method

  1. Create a variable named another_str_variable and assign string value "Python is fun, fun, and fun." to the variable. The string has 3 substrings 'fun'. But we will replace first 2 substrings 'fun' with the string 'awesome' using count.
  2. Apply the replace method (another_str_variable.replace('fun', 'awesome', 2)) to the string variable another_str_variable specifying the old substring 'fun', new string 'awesome', and occurrences of substring '2'.

    This method will replace first 2 occurrences of substring 'fun' of the string with the new string 'awesome'. Assign the result to a new variable called replaced_new_string and get the output using print() function.

Please take a closer look at the following example:

Example of using str.replace() method with count

Output of the above example
Example using count: Python is awesome, awesome, and fun.

Live Code Playground

In the following Python code editor, you can practice the above code by creating more string variables and remove substring of the string using str.replace() method. Click on the 'Execute Code' button to execute the code; the executed output will be displayed in the following Python Code Output frame. Practice until you become comfortable and proficient with your code.

Python logo Python Online Editor
Python Code Output