search

What is the use of the "replace" method in a Python string?

The **replace** method in a Python string is used to replace a specified substring with another substring. It returns a new string with the specified replacements made. The original string remains unchanged.

Here's an example:

text = "The quick brown fox jumps over the lazy dog."
replaced_text = text.replace("fox", "cat")
print(replaced_text)
# Output: "The quick brown cat jumps over the lazy dog."

You can also specify the maximum number of replacements to make:

text = "The quick brown fox jumps over the lazy dog. The fox is fast."
replaced_text = text.replace("fox", "cat", 1)
print(replaced_text)
# Output: "The quick brown cat jumps over the lazy dog. The fox is fast."

Related Questions You Might Be Interested