Syntax and Parameters
str.replace() method in Python is used to replace occurrences of a specified substring within a string with another substring. It was added to the language from the early days and still is one of the most used string methods nowadays.
string.replace(old, new, count)
string: The original string on which the replacement operation is performed.
old: The substring to be replaced.
new: The substring that replaces the occurrences of the old substring.
count(optional): Specifies the maximum number of replacements to be made. If not provided, all occurrences of the old substring are replaced.
replace() method searches for the old substring in the string and replaces it with the new substring. It returns a new string with the replacements applied, leaving the original string unchanged.
Some examples of using the
str.replace() method in Python.
In this example, we will Replace a substring with another substring in a string:
text = "Hello, Sling Academy!" new_text = text.replace("Hello", "Hi") print(new_text)
Hi, Sling Academy!
Multiple Limited Replacements
In this example, we will replace a substring with another substring in a string, but only a limited number of times.
text = "hello world, hello world, hello world, hello world, hello world" # replace only the first three occurrences new_text = text.replace("hello", "hi", 3) print(new_text)
hi world, hi world, hi world, hello world, hello world
This example demonstrates chaining
replace() calls to perform multiple replacements:
text = "Welcome to Sling Academy!" text = text.replace("!","").replace(" ", "_") print(text)
That’s it. Happy coding & have a nice day!