![]() |
VOOZH | about |
In this article, we will discuss how to replace only the duplicate occurrences of certain words in a string that is, replace a word from its second occurrence onwards, while keeping its first occurrence unchanged.
Example:
Input: Gfg is best. Gfg also has Classes now. Classes help understand better.
Output: Gfg is best. It also has Classes now. They help understand better.
This is the cleanest and most efficient approach. We use a set to keep track of seen words and a list comprehension to perform replacements in a single line.
Steps:
Gfg is best . It also has Classes now. They help understand better .
Explanation:
This approach uses regex patterns to detect repeated occurrences of target words and replaces them using re.sub().
Steps:
Gfg is best . It also has Classes now. They help understand better .
Explanation:
This is a more explicit and beginner-friendly approach using loops and sets. It manually iterates through the words, tracks first occurrences, and replaces duplicates.
Gfg is best . It also has Classes now. They help understand better .
Explanation:
This method uses the list.index() function inside a list comprehension to find if a word has appeared before. It replaces only the repeated words and keeps the first one as it is.
Gfg is best . It also has Classes now. They help understand better .
Explanation: