Python String replace() Method
The replace()
method returns a new string replacing some or all occurrences of a specified substring with another substring.
Syntax
string.replace(old, new, count)
Parameters
old
: The substring you want to replace.
new
: The substring you want to replace the old substring with.
count
(Optional): The number of times you want to replace the old
substring. If omitted, all occurrences are replaced.
Return Value
Returns a new string with the specified replacements. The original string remains unchanged since strings are immutable in Python.
Examples
Basic Usage
text = "Python is awesome. Python is easy to learn"
new_text = text.replace("Python", "Java")
print(new_text) # Output: Java is awesome. Java is easy to learn
Using the count
Parameter
You can provide the count
parameter to the replace()
method to replace the substring only a specific number of times.
text = "Python is awesome. Python is easy to learn. Python is very popular"
new_text = text.replace("Python", "Java", 2)
print(new_text) # Output: Java is awesome. Java is easy to learn. Python is very popular
In this example, only the first two occurrences of substring "Python"
is replaced with "Java"
.
Case-sensitivity
The replace()
method is case-sensitive, meaning it treats uppercase and lowercase letters as distinct characters.
text = "Python is awesome, python is easy to learn."
new_text = text.replace("Python", "Java")
print(new_text) # Output: Java is awesome, python is easy to learn.
In this example, the replace()
method replaces the exact match substring "Python"
(with an uppercase "P"
) with "Java"
. However, the substring "python"
(with a lowercase "p"
) remains unchanged because replace()
method is case-sensitive.