String replace() Method in Python

Python String replace() Method

The replace() method in Python is used to create a new string by replacing all occurrences of a specified substring with another substring. It is a commonly used string manipulation method and is part of Python's built-in string functions.

The syntax of the replace() method is as follows:

new_string = original_string.replace(old_substring, new_substring, count)

Here's a breakdown of the parameters:

  • original_string: This is the original string on which you want to perform the replacement.

  • old_substring: This is the substring you want to replace in the original_string.

  • new_substring: This is the substring that will replace all occurrences of the old_substring.

  • count (optional): It specifies the maximum number of occurrences to replace. If not provided, all occurrences of the old_substring will be replaced.

The replace() method returns a new string with the specified replacements. It does not modify the original string.

Let's look at some examples to better understand its usage:

# Example 1:
original_string = "Hello, World!"
new_string = original_string.replace("Hello", "Hi")
print(new_string)  # Output: "Hi, World!"

# Example 2:
sentence = "I love Python, Python is great!"
new_sentence = sentence.replace("Python", "JavaScript")
print(new_sentence)
# Output: "I love JavaScript, JavaScript is great!"

# Example 3 (with count):
text = "one one, two one, three one, four one, one"
new_text = text.replace("one", "X", 2)
print(new_text)  # Output: "X X, two one, three one, four one, one"

In the first example, we replaced "Hello" with "Hi" in the original string. In the second example, we replaced all occurrences of "Python" with "JavaScript." In the third example, we replaced the first two occurrences of "one" with "X" by specifying count=2.