Replace Duplicate Occurrences in String Using Python



In this article, we will explore different ways to replace duplicate occurrences in a string. Before understanding the solution let's try to understand the problem statement with an example.

Consider a string "Ram lives in Hyderabad. Ram is studying in class 10. Ram is the class Monitor of the class." In this string "Ram" appears multiple times we need to replace the duplicate occurrences with 'He', keeping the first occurrence unchanged.

Replacing Duplicate Occurrences in a String

Following are the multiple ways to replace duplicate occurrences in a string ?

Using 'List' Comprehension

When it is required to replicate the duplicate occurrence in a string, the keys, the ?index' method, and list comprehension can be used. The list comprehension is a shorthand to iterate through the list and perform operations on it. The index method returns the index of the specific value/iterable, Below is a demonstration of the same

Example

Following is an example to replace duplicate occurrence in a string using list comprehension ?

my_str = "Jane is the best . Jane loves to cook. Jane and Will cook together"
print("Original string : ",my_str)
replace_dict = {'Jane':'She' }
my_list = my_str.split(' ')
my_result = ' '.join([replace_dict.get(val) if val in replace_dict.keys() and my_list.index(val) != idx else val for idx, val in enumerate(my_list)])
print("Replaced string : ",my_result)

Following is the output of the above code ?

Original string:  Jane is the best. Jane loves to cook. Jane and Will cook together
Replaced string:  Jane is the best. She loves to cook. She and Will cook together

Using 'for' loop

In Python, duplicate occurrences in the string can be replaced using the for() loop. Firstly we need to convert the string into a list using the split() method. In this method, we need to initialize a variable to False if a duplicate word is found for the first time it is updated by True again for another occurrence it is replaced with another word. After replacement, we need to convert the list back to a string using the join() method.

Example

Here, firstly the string is converted to a list. In the given string "Swathi" appeared multiple times. We have replaced the duplicate occurrences with "she" using for loop and again converted back to string ?

my_str ="Swathi works in TCS. Swathi is working as a developer. Swathi has 10 years of work experience."
print("Original string : ", my_str)
# Split the string into words
words = my_str.split()
# Track whether we've seen 'Swathi' before
seen_jane = False
# Replace only the second and further occurrences of 'Swathi'
for i in range(len(words)):
    if words[i] == "Swathi":
        if seen_jane:
            words[i] = "She"
        seen_jane = True
		
# Reconstruct the string
new_str = " ".join(words)
print("Replaced String:", new_str)

Output

Following is the output of the above code ?

Original String:  Swathi works in TCS. Swathi is working as a developer. Swathi has 10 years of work experience.
Replaced String: Swathi works in TCS. She is working as a developer. She has 10 years of work experience.

Using 'enumerate()' method

The enumerate() is an in-built function used to count each element in a list, tuple, or any data structure that can be iterated. This function when iterated through the loop returns the index value and element of the particular sequence.

Using enumerate() function is used to replace multiple occurrences in a string. In this method, we first convert the string into a list using the split() method. Then, we initialize a dictionary to map the words we want to replace. We also initialize an empty set() to keep track of words that have already been encountered. The loop iterates over the list of words, and if a word is in the dictionary and has already been encountered in the set, it replaces the word with its mapped value from the dictionary. If the word hasn't been encountered yet, it is added to the set. Finally, the list is converted back into a string.

Example

In the following example we have replaced the duplicate occurrences of a string using the enumerate() function ?

# initializing string 
my_Str = "Raju went to school. Raju is studying in the 8th class. Raju is a clever boy in the class."
# printing original string 
print("Original String: ",my_Str) 
# initializing replace mapping 
dict_1 = {'Raju' : 'he'} 
# Replace duplicate Occurrence in String 
# Using split() + enumerate() + loop 
my_list = my_Str.split(' ') 
my_set = set() 
for idx, ele in enumerate(my_list): 
    if ele in dict_1: 
        if ele in my_set: 
            my_list[idx] =dict_1[ele] 
        else: 
            my_set.add(ele) 
Rep_Str = ' '.join(my_list) 
# printing result 
print("Replaced String :", Rep_Str) 

Following is the output of the above code ?

Original String:  Raju went to school. Raju is studying in the 8th class. Raju is a clever boy in the class.
Replaced String: Raju went to school. He is studying in the 8th class. He is a clever boy in the class.
Updated on: 2025-01-22T14:31:12+05:30

709 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements