replace() method is used to replace a specified substring with another substring in a string. It returns a new string with the replacements applied, while the original string remains unchanged.
s = "Python is fun. Python is powerful."
res = s.replace("Python", "Coding")
print(res)
Output
Coding is fun. Coding is powerful.
Explanation:
- replace("Python", "Coding") replaces every occurrence of "Python" with "Coding".
- A new string is returned with the updated values, original string s remains unchanged.
Syntax
string.replace(old, new, count)
Parameters:
- old: substring that needs to be replaced.
- new: substring that will replace old.
- count (optional): Specifies the maximum number of replacements to perform. If omitted, all occurrences are replaced.
Return Value: A new string with the specified replacements applied. The original string is not modified because strings in Python are immutable.
Examples
Example 1: 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 2: 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".
Example 3: In this example, replace() is used multiple times to clean and reformat a phone number.
phone = "123-456-7890"
res = phone.replace("-", " ")
print(res)
Output
123 456 7890
Explanation: replace("-", " ") replaces each hyphen (-) with a space.