In python, the string replace() method is useful to replace the specified substring or character in all occurrences of the given string.
Following is the pictorial representation of string replace() method functionality in python.
If you observe the above diagram, we are replacing the "Hi
" word in the given string “Hi Guest Hi
” with "Hello
" using the python replace method. After completing string replacement, the replace() method will return a new string like "Hello Guest Hello
".
Following is the syntax of defining a string replace method in python.
If you observe the above syntax, the replace()
method accepts three parameters (old string/char, new string/char, count), and the count parameter is optional.
Following is the example of replacing all specified string occurrences using the replace()
method in python.
If you observe the above example, we are replacing the substrings in the given strings with the required substrings/characters using the replace()
method without specifying the count
parameter.
When you execute the above python program, you will get the result as shown below.
In the above example, we didn’t mention any limit (count
) on the number of replacements. The replace()
method replaced all the occurrences of substrings/characters in the given strings.
If you want to limit the number of strings replacement, you need to mention the count
parameter value in the replace()
method.
Following is the example of limiting the number of substrings replacement with count
parameter value using replace()
method.
If you observe the above example, we are limiting the string replacement by specifying the count
parameter value in replace()
method.
When you execute the above python program, you will get the result as shown below.
This is how you can use a string replace()
method in python to replace all substring occurrences in the given string based on your requirements.