Python String replace() Method
The replace() method returns a new string where all occurrences of a specified substring are replaced with another substring. It does not modify the original string because Python strings are immutable.
Example : This example replaces every occurrence of a substring in the given string, creating a fully updated new string.
s = "Python is fun. Python is powerful."
res = s.replace("Python", "Coding")
print(res)
Output
Coding is fun. Coding is powerful.
Syntax
string.replace(old, new, count)
Parameters:
- old: Substring to be replaced.
- new: Substring to insert in place of old.
- count (optional): Maximum number of replacements. If not provided, all occurrences are replaced.
Return Value: Returns a new string with the specified replacements. The original string remains unchanged.
Examples
Example 2: Here, only the first occurrence of a substring is replaced using the count parameter.
s = "apple apple apple"
res = s.replace("apple", "orange", 1)
print(res)
Output
orange apple apple
Explanation: s.replace("apple", "orange", 1) replaces "apple" only once due to count=1.
Example 3: This example demonstrates that replace() treats uppercase and lowercase characters as different, replacing only exact matches.
s = "Hello World! hello world!"
res1 = s.replace("Hello", "Hi")
res2 = s.replace("hello", "hi")
print(res1)
print(res2)
Output
Hi World! hello world! Hello World! hi world!
Explanation:
- s.replace("Hello", "Hi") affects only the capitalized "Hello".
- s.replace("hello", "hi") affects only the lowercase "hello".