Use Python’s str.replace() method to replace a substring with another string. You can replace every occurrence or limit the operation to a specific number of matches.
Replace a Substring with str.replace() in Python
The str.replace() method searches a string for an exact substring and returns a new string in which the matching occurrences are replaced.
Python strings are immutable, so replace() does not modify the original string. Assign the returned value to a variable when you need to keep the updated text.
Syntax of Python str.replace()
The syntax of string.replace() function is
string.replace(old, new, count)
The count argument is optional. The method may therefore be called with either two or three arguments:
string.replace(old, new)
string.replace(old, new, count)
| Parameter | Required | Description |
|---|---|---|
old | Yes | The exact substring to search for. |
new | Yes | The string that replaces each selected occurrence of old. |
count | No | The maximum number of occurrences to replace, starting from the left. When omitted, all occurrences are replaced. |
Return Value of str.replace()
The method returns a new string. If the specified old substring is not found, it returns a string with the same value as the original.
The replacement is case-sensitive. For example, replacing 'cat' does not replace 'Cat'.
Python String Replacement Examples
1. Replace All Occurrences of a Substring
When count is omitted, Python replaces every occurrence of the specified substring. Replacement is based on substring matching, so 'cat' is also found inside words such as 'concat' and 'catalog'.
Python Program
s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'
s2 = s1.replace(old, new)
print(s2)
Output
dog says hey. condog dogalog.
Because replace() matches substrings rather than complete words, all three occurrences of 'cat' are replaced.
2. Replace Only N Occurrences
Pass an integer as the third argument to limit the maximum number of replacements. Python processes matching occurrences from left to right.
Python Program
s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'
s2 = s1.replace(old, new, 2)
print(s2)
Output
dog says hey. condog catalog.
Only the first two occurrences are replaced. The third occurrence, inside 'catalog', remains unchanged.
3. Replace Only the First Occurrence
Set count to 1 when only the first matching substring should be replaced.
Python Program
s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'
s2 = s1.replace(old, new, 1)
print(s2)
Output
dog says hey. concat catalog.
4. Keep the Original String Unchanged
Calling replace() does not update the source string in place. The returned string must be assigned if you want to use the replaced value.
message = 'Python is simple. Python is readable.'
updated_message = message.replace('Python', 'The language')
print(message)
print(updated_message)
Output
Python is simple. Python is readable.
The language is simple. The language is readable.
5. Remove a Substring Using an Empty Replacement
To remove matching text, replace it with an empty string.
text = 'Order ID: #1045'
cleaned_text = text.replace('#', '')
print(cleaned_text)
Output
Order ID: 1045
6. Replace Text Without a Case-Sensitive Match
The replace() method matches case exactly. In the following example, only the lowercase occurrence is replaced.
text = 'Python and python'
result = text.replace('python', 'Java')
print(result)
Output
Python and Java
For case-insensitive or pattern-based replacement, use Python’s re.sub() function from the re module.
7. Replace Multiple Different Substrings
You can chain replace() calls when a small, known set of different substrings must be replaced.
text = 'red, green, blue'
result = text.replace('red', 'orange').replace('blue', 'purple')
print(result)
Output
orange, green, purple
Important str.replace() Behaviors
replace()returns a new string and does not modify the original string.- Matching is case-sensitive.
- The method replaces exact substrings, not necessarily complete words.
- When
countis omitted, all matching occurrences are replaced. - When
countis supplied, replacements are made from left to right. - If
oldis not found, the returned value has the same text as the original string. - An empty
newstring removes the selected substring.
Python str.replace() Frequently Asked Questions
Does str.replace() modify the original Python string?
No. Python strings are immutable. The method returns a new string, so assign the result to a variable when you need the changed value.
How do I replace only the first occurrence in a Python string?
Pass 1 as the count argument: text.replace(old, new, 1).
Is Python string replacement case-sensitive?
Yes. 'python' and 'Python' are different substrings. Use regular expressions when case-insensitive replacement is required.
How do I remove text with str.replace()?
Replace the unwanted substring with an empty string, as in text.replace('remove this', '').
Does str.replace() replace complete words only?
No. It replaces exact substring matches wherever they occur. Replacing 'cat' can therefore also change 'catalog'. Use tokenization or regular-expression word boundaries when only complete words should match.
Summary of Python String Replacement
Use str.replace(old, new) to replace all matching substrings and str.replace(old, new, count) to limit the number of replacements. The method is case-sensitive, processes limited replacements from left to right, and returns a new string without changing the original.
In this Python Tutorial, we learned how to replace, remove, and limit substring replacements using the str.replace() method.
TutorialKart.com