The replace() method in Python is a built-in string method used to replace all occurrences of a specified substring within a string with another substring. It returns a new string with the replacements made.
Syntax:
string.replace(old, new, count)
old: This parameter specifies the substring that you want to replace. All occurrences of this substring within the string will be replaced.
new: This parameter specifies the substring that will replace the occurrences of the old substring.
count (optional): This parameter determines the number of occurrences to be replaced. If count is not specified, all occurrences of the old substring will be replaced.
How to use the replace() method:
string = "Hello, World!"
new_string = string.replace("Hello", "Hi")
print(new_string) # Output: Hi, World!
Example 1
Replacing multiple substrings.
string = "The quick brown fox jumps over the lazy dog."
replaced_string = string.replace("quick", "fast").replace("brown", "red").replace("lazy", "active")
print(replaced_string) # Output: The fast red fox jumps over the active dog.
Example 2
Case-insensitive replacement.
string = "The cat chased the CAT."
new_string = string.replace("cat", "dog", 1)
print(new_string) # Output: The dog chased the CAT.
Example 3
Replace specific time and event-related substrings in a string.
string = "Let's meet at 9:30 PM for dinner."
replacements = {
"9:30": "7:00",
"PM": "AM",
"dinner": "breakfast"
}
for old, new in replacements.items():
string = string.replace(old, new)
print(string) # Output: Let's meet at 7:00 AM for breakfast.