Python String - Replace all occurrences


Python String - Replace all occurrences

In Python, you can use the str.replace() method to replace all occurrences of a substring in a string.

The syntax to use replace() function is

result_string = original_string.replace(old_string, new_string)

where the replace() function uses replaces all occurrences of old_string with the new_string string in original_string.

Example to replace all occurrences

In this program, we are given a string in original_string, and we need to replace all the occurrences of "apple" with "banana" using string replace() function.

Python Program

original_string = "apple is a fruit. apple is good."
old_string = "apple"
new_string = "banana"

# Replace all the occurrences
result_string = original_string.replace(old_string, new_string)

print(result_string)

Output

banana is a fruit. banana is good.