In python replace() is an inbuilt function which returns a string by replacing sub-string with another sub-string, with all occurrences of specified numbers.
Syntax
original-string.replace(old-sub-string, new-sub-string[, max])
Parameters:
- old-substring: (Required): The old sub-string to replace
- new-substring: (Required): The new sub-string to replace with
- max: (Optional): Specify the number of occurrence of sub-string to replace, Default: All Occurrence
Return Value: String
Returns a new string which is a copy of “original-string” with all or specified occurrence of old sub-string replaced with new sub-string
Example:
# Python3 program to explain working of replace() method
string = "Hello Stechies, Hello Python, Hello Programming, Hello Development"
# Replace sub-string Hello with Hi
print(string.replace("Hello", "Hi"))
# Replace sub-string Hello with Hi only 3 occurrence
print(string.replace("Hello", "Hi", 3))
# Check is replace() is case-sensitive
print(string.replace("hello", "Hi", 3))
Output:
Hi Stechies, Hi Python, Hi Programming, Hi Development
Hi Stechies, Hi Python, Hi Programming, Hello Development
Hello Stechies, Hello Python, Hello Programming, Hello Development
Note: replace function is case-sensitive