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
-
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'. -
Apply the replace method (
str_variable.replace('fun', 'awesome')
) to the string variablestr_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 calledreplaced_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
-
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. -
Apply the replace method (
another_str_variable.replace('fun', 'awesome', 2)
) to the string variableanother_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 calledreplaced_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.