This blog replaces the string using the replace() method. This method is used to replace the specified string with another string.
Syntax
string.replace(old, new, count)
old :- The string to search for
new : – String to replace the old string
count :- Determine number to replace the string
Example : Replacing the city name in the string
In the example, we have the string “I like to live in Paris,” which needs to be changed into “I like to live in London” Replacing the city name in the string The program is very simple and makes use of the replace() method to change the city name from Paris to London. This method will search for the word “Paris” and replace it with “London”
original_String = "I like to live in Paris"
print('Original string: ',original_String)
replace_string = original_String.replace('Paris','London')
print('Replaces String: ',replace_string)
Output
Original string: I like to live in Paris
Replaces String: I like to live in London
Example : Replacing all instances of the string
original_String = "I works in the information technology industry. I was reading the book. I visited the village."
print('Original string: ',original_String)
replace_string = original_String.replace('I','He')
print('Replaces String: ',replace_string)
Output
Original string: I works in the information technology industry. I was reading the book. I visited the village.
Replaces String: He works in the information technology industry. He was reading the book. He visited the village.
Example : Replacing the first two occurrences of the string
original_String = "I works in the information technology industry. I was reading the book. I visited the village."
print('Original string: ',original_String)
replace_string = original_String.replace('I','He',2)
print('Replaces String: ',replace_string)
Output
Original string: I works in the information technology industry. I was reading the book. I visited the village.
Replaces String: He works in the information technology industry. He was reading the book. I visited the village.