The `replace()` function in Python is used to replace occurrences of a specified substring within a string with another substring. This function does not modify the original string but returns a new string with the replacements.
Syntax
str.replace(old, new, count)
`old`: The substring you want to replace.
`new`: The substring that will replace the old substring.
`count` (optional): The number of times you want to replace the old substring. If omitted, all occurrences will be replaced.
Example 1: Basic Usage
text = "Hello, world! Hello, everyone!" new_text = text.replace("Hello", "Hi") print(new_text)
Output
Hi, world! Hi, everyone!
Explanation
In this example, the word “Hello” is replaced with “Hi” in the entire string. The `replace()` function returns a new string with the replacements.
Example 2: Using the `count` Parameter
text = "Hello, world! Hello, everyone! Hello, Python!" new_text = text.replace("Hello", "Hi", 2) print(new_text)
Output
Hi, world! Hi, everyone! Hello, Python!
Explanation
Here, only the first two occurrences of “Hello” are replaced with “Hi”. The `count` parameter limits the number of replacements.
Example 3: Replacing Characters
text = "apple, banana, cherry" new_text = text.replace(",", ";") print(new_text)
Output
apple; banana; cherry
Explanation
In this example, all commas in the string are replaced with semicolons. This is useful for formatting strings.
Example 4: Replacing with an Empty String
text = "This is an example sentence." new_text = text.replace("example ", "") print(new_text)
Output
This is an sentence.
Explanation
In this example, the substring “example ” is replaced with an empty string, effectively removing it from the original string.
The `replace()` function is a simple yet powerful tool for manipulating strings in Python.