4.Examples of Python’s replace() Method
Example 1: Basic replacement of all occurrences
text = "apple banana apple grape"
result = text.replace("apple", "orange")
print(result)
# Output: orange banana orange grape
'
Explanation:
Every occurrence of “apple” is replaced with “orange” throughout the string.
Example 1: Basic replacement of all occurrences
text = "apple banana apple grape"
result = text.replace("apple", "orange")
print(result)
# Output: orange banana orange grape
'
Explanation:
Every occurrence of “apple” is replaced with “orange” throughout the string.
Example 2: Replace with a limited number of occurrences (count=1)
text = "apple banana apple grape"
result = text.replace("apple", "orange", 1)
print(result)
# Output: orange banana apple grape
Explanation:
Only the first “apple” is replaced, because the count value is set to 1.
Example 3: Replacing a substring that does not exist
text = "hello world"
result = text.replace("python", "java")
print(result)
# Output: hello world
Explanation:
Since “python” isn’t found in the string, no changes are made.
Example 4: Replacing an empty string (“”) – special behavior
text = "hello"
result = text.replace("", "-")
print(result)
# Output: -h-e-l-l-o-
Explanation:
When the substring to replace is “” (empty), Python inserts the replacement between every character and also at the start and end.
Example 5: Replacing spaces with another character
text = "a b c d e"
result = text.replace(" ", "|")
print(result)
# Output: a|b|c|d|e
Explanation:
Every space is replaced with “|”, which is useful when formatting or cleaning text.