The replace()
function is a string method in Python that returns a new string with all occurrences of a specified substring replaced with another specified substring. The method syntax is string.replace(old, new)
, where old
is the substring to be replaced, and new
is the substring to replace it with.
Parameter Values
Parameter | Description |
---|---|
old | The substring to be replaced in the original string. |
new | The substring that will replace the 'old' substring in the original string. |
count | An optional parameter specifying the maximum number of replacements to make. |
Return Values
The replace()
method returns a new string with the replaced content.
How to Use replace()
in Python
The replace()
method returns a new string with all occurrences of a specified value replaced with another value.
text = 'Hello, world!'\nnew_text = text.replace('world', 'Python')\nprint(new_text) # Output: Hello, Python!
The replace()
method is case-sensitive.
text = 'Python is awesome!'\nnew_text = text.replace('python', 'Java')\nprint(new_text) # Output: Python is awesome!
The replace()
method can replace multiple occurrences of the specified value.
text = 'Python programming is fun and Python is powerful'\nnew_text = text.replace('Python', 'JavaScript')\nprint(new_text) # Output: JavaScript programming is fun and JavaScript is powerful