How is “replace” used in Python?
In Python, replace() is a string method used to substitute specified content within a string.
Here is the syntax for the replace() method:
string.replace(old, new, count)
In this case, ‘string’ is the string to be replaced, ‘old’ is the content to be replaced, ‘new’ is the replacement content, and ‘count’ is an optional parameter specifying the number of replacements.
Here is an example using the replace() method:
string = "Hello World!"
new_string = string.replace("World", "Python")
print(new_string)
The output is: Hello Python!
In the above example, the replace() method replaces “World” with “Python” in the string and returns the new string with the replacement.
If you want to specify the number of replacements, you can set the count parameter to a positive integer value. For example:
string = "Hello World!"
new_string = string.replace("o", "O", 2)
print(new_string)
The output results in: Hello World!
In the above example, the replace() method replaces the first two lowercase letters “o” with uppercase letter “O” in the string.