Skip to main content

How to replace a substring in a string in Python

How to replace a substring in a string in Python.

Here's a step-by-step tutorial on how to replace a substring in a string using Python:

  1. Start by defining the original string that you want to modify. Let's say the original string is stored in a variable called original_string.

  2. Determine the substring that you want to replace in the original string. Let's call this substring old_substring.

  3. Decide on the new substring that you want to replace the old substring with. Let's call this new_substring.

  4. Use the replace() method to replace the old substring with the new substring. The syntax for using the replace() method is as follows:

   modified_string = original_string.replace(old_substring, new_substring)

This will create a new string called modified_string that contains the modified version of the original string. Note that strings are immutable in Python, so the replace() method does not modify the original string directly, but rather returns a new string.

Here's an example to illustrate this:

   original_string = "Hello, World!"
old_substring = "Hello"
new_substring = "Hi"

modified_string = original_string.replace(old_substring, new_substring)
print(modified_string)

Output:

   Hi, World!
  1. If you want to replace all occurrences of the old substring in the original string, you can pass an optional third argument to the replace() method called count. This argument specifies the maximum number of replacements to make. By default, the count argument is set to replace all occurrences. Here's an example:
   original_string = "Hello, Hello, Hello!"
old_substring = "Hello"
new_substring = "Hi"

modified_string = original_string.replace(old_substring, new_substring)
print(modified_string)

Output:

   Hi, Hi, Hi!

If you want to replace only the first occurrence or a specific number of occurrences, you can specify the count argument accordingly.

  1. It's important to note that the replace() method is case-sensitive. If you want to perform a case-insensitive replacement, you can convert both the original and new substrings to the same case (upper or lower) before calling the replace() method.

That's it! You've successfully replaced a substring in a string using Python. Feel free to experiment with different strings and substrings to get a better understanding of how the replace() method works.