Python String - Replace first N occurrences
Python String - Replace first N occurrences
To replace the first n occurrences in a Python string, you can use string replace() method with the optional __count parameter.
In this tutorial, we shall see the step by step process to replace only the first n occurrences of an old substring with a new substring in a string, using string replace() method, with examples.
Steps to replace only the first N occurrences in a string
- Given string in x.
x = "apple apple apple apple apple"
- Given limit on the number of replacements in n.
n = 3
- Given old substring, and new substring in old and new variables respectively.
old = 'apple'
new = 'fig'
- Call replace() method on string x and pass the values: old, new, and n as arguments respectively. The replace() method returns a new string, where the old substring is replaced with new substring for only the first n number of occurrences of old substring in the string x.
x.replace(old, new, n)
Program
The complete program to replace only the first n occurrences in a Python string using replace() method is given below.
Python Program
# Given string
x = "apple apple apple apple apple"
# Limit on number of replacements
n = 3
# Old and new strings
old = 'apple'
new = 'fig'
# Replace first n occurrences
result = x.replace(old, new, n)
# Print the result string
print(result)
Output
fig fig fig apple apple
We specified to replace only the first three occurrences of the old substring "apple"
with a new replacement string "fig"
in the original string.
Summary
In this Python Strings tutorial, we learned how to replace only the first n occurrences in a string based using replace() method, with examples.