The replace()
method in Python is used to replace a specified substring with another substring within a string. It creates a new string with the replacement since strings in Python are immutable.
Syntax
old
: The substring to be replaced.new
: The substring to replaceold
.count
(optional): The number of occurrences to replace. If omitted, all occurrences will be replaced.
Examples
1. Replace All Occurrences
Output:
2. Replace Limited Occurrences
Output:
3. Case-Sensitive Replacement
The replace()
method is case-sensitive, so it differentiates between uppercase and lowercase.
Output:
4. Replacing Spaces or Special Characters
Output:
5. Using replace()
with Empty String
You can remove a substring by replacing it with an empty string.
Output:
Key Points
- Immutability: The
replace()
method doesn’t modify the original string; it returns a new string. - Case-Sensitivity: Matches are case-sensitive.
- Efficient for Replacements: Suitable for replacing specific substrings.
Common Use Cases
- Replacing specific words in a document.
- Formatting strings (e.g., replacing spaces with underscores).
- Removing unwanted characters from a string.
The replace()
method is versatile and frequently used for text manipulation in Python.