Last Updated : 28 Oct, 2024
The replace() method replaces all occurrences of a specified substring in a string and returns a new string without modifying the original string.
Let’s look at a simple example of replace() method.
Python
s = "Hello World! Hello Python!"
# Replace "Hello" with "Hi"
s1 = s.replace("Hello", "Hi")
print(s1)
Hi World! Hi Python!
Explanation: Here, "Hello" is replaced by "Hi" throughout the string, resulting in "Hi World! Hi Python!".
Note: Since replace() creates a new string, the original string remains unchanged.
Syntax of String replace() MethodParametersstring.replace(old, new, count)
By using the optional count parameter, we can limit the number of replacements made. This can be helpful when only a specific number of replacements are desired.
Python
s = "apple apple apple"
# Replace "apple" with "orange" only once
s1 = s.replace("apple", "orange", 1)
print(s1)
orange apple apple
Explanation: replace() method only replaces the first instance of "apple" because we specified count=1.
Case Sensitivity in replace()The replace() method is case-sensitive, it treats uppercase and lowercase characters as distinct. If we want to replace both cases then we have to use additional logic.
Python
s = "Hello, World! hello, world!"
# Replace only lowercase 'hello'
s1 = s.replace("hello", "hi")
print(s1)
# Replace only uppercase 'Hello'
s2 = s.replace("Hello", "Hi")
print(s2)
Hello, World! hi, world! Hi, World! hello, world!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4