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:
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
.Determine the substring that you want to replace in the original string. Let's call this substring
old_substring
.Decide on the new substring that you want to replace the old substring with. Let's call this
new_substring
.Use the
replace()
method to replace the old substring with the new substring. The syntax for using thereplace()
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!
- 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 calledcount
. This argument specifies the maximum number of replacements to make. By default, thecount
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.
- 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 thereplace()
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.