Python - Replacing Nth occurrence of multiple characters in a String with the given character
Last Updated :
15 Jan, 2025
Improve
Replacing the Nth occurrence of multiple characters in a string with a given character involves identifying and counting specific character occurrences.
Using a Loop and find()
Using a loop and find()
method allows us to search for the first occurrence of a substring within each list element. This approach is useful when you need to identify and process specific patterns or characters within the list elements.
s = "hello world, hello everyone"
chars = ['h', 'e']
n = 2
replacement = 'X'
result = s
for char in chars:
count = 0
i = -1
while count < n:
i = result.find(char, i + 1)
if i == -1:
break
count += 1
if i != -1:
result = result[:i] + replacement + result[i + 1:]
print(result) # Output: "hello world, Xllo everyone"
Output
hello world, XXllo everyone
Explanation:
- The code iterates over each character in
chars
and usesfind()
to locate the N-th occurrence of that character in the string. - Upon finding the N-th occurrence, it replaces the character with
X
and updates the string; if the N-th occurrence is not found, it leaves the string unchanged.
Using enumerate
and String Slicing
Using enumerate()
with string slicing allows efficient iteration through a string while keeping track of the index. This technique is useful for modifying specific characters based on their position in the string.
s = "banana island eagle"
targets = {'a', 'e', 'i'}
n = 2
replacement = '*'
count = {char: 0 for char in targets}
for i, char in enumerate(s):
if char in targets:
count[char] += 1
if count[char] == n:
output = s[:i] + replacement + s[i+1:]
break
else:
output = s
print(output)
Output
ban*na island eagle
Explanation:
- The code tracks occurrences of target characters (
a
,e
,i
) in the string. - Upon finding the N-th occurrence, it replaces that character with
*
and exits the loop.