Usage
The replace()
method returns a copy of string with all occurrences of old substring replaced by new.
By default, all occurrences of the substring are removed. However, you can limit the number of replacements by specifying optional parameter count.
Syntax
string.replace(old,new,count)
Parameter | Condition | Description |
old | Required | A string you want to replace |
new | Required | A string you want to replace old string with |
count | Optional | An integer specifying number of replacements to perform Default is all occurrences |
Basic Example
Let’s say you want to remove all occurrences of the word “Hello” in the string:
text = "Hello? Hello, can you hear me? Hello...?"
new_text = text.replace("Hello", "")
print(new_text)
# Output: "? , can you hear me? ...?"
Limiting Removals
Note that replace()
removes all occurrences of the substring by default. You can limit the number of replacements by specifying the count
parameter.
For example, to remove only the first occurrence of the substring “Hello”:
text = "Hello? Hello, can you hear me? Hello...?"
new_text = text.replace("Hello", "", 1)
print(new_text)
# Output: "? Hello, can you hear me? Hello...?"
replace() Always Returns a New String
It’s important to remember that the replace()
method doesn’t modify the original string. Instead, it always returns a new string with the changes you’ve made. If you want to keep the modified version, you need to assign it back to a variable (or a new variable).
text = "Hello? Hello, can you hear me? Hello...?"
text.replace("Hello", "") # This change isn't saved anywhere
print(text)
# Output: "Hello? Hello, can you hear me? Hello...?" (still the original)
# To save the change:
text = text.replace("Hello", "")
print(text)
# Output: "? , can you hear me? ...?"
Removing Multiple Substrings
Here are a couple of ways you can remove multiple substrings from a piece of text:
For a small number of removals, you can chain multiple replace()
calls together.
text = "Hello? Hello, can you hear me? Hello...?"
new_text = text.replace("Hello", "").replace("?", "")
print(new_text)
# Output: " , can you hear me ..."
If you have many substrings to remove, chaining replace()
calls can become cumbersome. A more organized approach is to define a list of the substrings you want to remove and loop through it:
text = "Hello? Hello, can you hear me? Hello...?"
replacements = ["Hello", "?", "can"]
for x in replacements:
text = text.replace(x, "")
print(text)
# Output: ", you hear me ..."