Python String - Replace first occurrence
Python String - Replace first occurrence
To replace only the first occurrence in a string in Python, you can use string replace() method. Pass the old and new strings as first and second arguments, and pass 1
for count parameter as third argument to replace only one occurrence.
For example, if given string is
"Hello, World! Hello, Universe!"
and we need to replace only the first occurrence of "Hello"
with "Hi"
, then the resulting string would be
"Hi, World! Hello, Universe!"
In this tutorial, you will learn how to replace the first occurrence in a string in Python using string replace() method, with example.
1. Replace first occurrence in string using string replace() method in Python
In this example, we are given a string in x
. We have to replace only the first occurrence of a specified old substring with a new value using replace() method.
Steps
- Given string is in x.
x = "Hello, World! Hello, Universe!"
- Given old substring and new (replacement) value in old_substring and new_substring respectively.
old_substring = "Hello"
new_substring = "Hi"
- Call replace() method on string x, and pass old_substring, new_substring, and 1 as arguments. The third parameter specifies the number of replacements to be done
x.replace(old_substring, new_substring, 1)
- The replace() method returns the resulting string. You may store the returned value in a variable, say result_string, and use it as per requirement.
Program
The complete Python program to replace the first occurrence in a string using Python string replace() method.
Python Program
# Input string
x = "Hello, World! Hello, Universe!"
# Substring to be replaced
old_substring = "Hello"
# Replacement string
new_substring = "Hi"
# Replace the first occurrence
result_string = x.replace(old_substring, new_substring, 1)
# Print the result
print(f"Original : {x}")
print(f"Result : {result_string}")
Output
Original : Hello, World! Hello, Universe!
Result : Hi, World! Hello, Universe!
Only the first occurrence of old substring has been replaced with the new substring.
Summary
In this tutorial of Python Examples, we learned how to replace only the first occurrence of a substring in a string using string replace() method, with the help of detailed step by step process and an example program.