Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Case insensitive string replacement in Python
Next article icon

Python – Replace duplicate Occurrence in String

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python strings, we can have problem in which we need to perform the replace of a word. This is quite common task and has been discussed many times. But sometimes, the requirement is to replace occurrence of only duplicate, i.e from second occurrence. This has applications in many domains. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using split() + enumerate() + loop 

The combination of above functions can be used to perform this task. In this, we separate the words using split. In this, we memoize the first occurrence in set and check if the value is saved before and then is replaced is already occurred. 

Python3




# Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
 
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. \
                Classes help understand better . '
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing replace mapping
repl_dict = {'Gfg' : 'It', 'Classes' : 'They' }
 
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
test_list = test_str.split(' ')
res = set()
for idx, ele in enumerate(test_list):
    if ele in repl_dict:
        if ele in res:
            test_list[idx] = repl_dict[ele]
        else:
            res.add(ele)
res = ' '.join(test_list)
 
# printing result
print("The string after replacing : " + str(res))
 
 
Output : 

The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better . The string after replacing : Gfg is best . It also has Classes now. They help understand better .

Time Complexity: O(n)

Space Complexity: O(n)

  Method #2 : Using keys() + index() + list comprehension 

This is yet another way in which this task can be performed. In this, we don’t require memoization. This is one liner approach to solve this problem. 

Python3




# Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using keys() + index() + list comprehension
 
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. Classes help understand better . '
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing replace mapping
repl_dict = {'Gfg' : 'It', 'Classes' : 'They' }
 
# Replace duplicate Occurrence in String
# Using keys() + index() + list comprehension
test_list = test_str.split(' ')
res = ' '.join([repl_dict.get(val) if val in repl_dict.keys() and test_list.index(val) != idx
                                else val for idx, val in enumerate(test_list)])
 
# printing result
print("The string after replacing : " + str(res))
 
 
Output : 

The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better . The string after replacing : Gfg is best . It also has Classes now. They help understand better .

Time Complexity: O(n)

Space Complexity: O(n)

Method #3 : Using  list comprehension + set + keys This is yet another way in which this task can be performed.

  • The code initializes a string variable named test_str with the value ‘Gfg is best . Gfg also has Classes now. Classes help understand better . ‘.
  • The code prints the original string using the print() function and string concatenation.
  • The code initializes a dictionary variable named repl_dict with key-value pairs, where each key is a string that needs to be replaced, and its corresponding value is the string to replace it with.
  • The code splits the test_str string into a list of words using the split() method, and initializes an empty set named seen to keep track of which words have been replaced.
  • The code uses a list comprehension to replace duplicate occurrences of words in the list of words generated in the previous step. The list comprehension iterates over each word in the list and checks if it is present in the repl_dict dictionary and also not present in the seen set. If the word is present in the dictionary and not in the seen set, it is replaced with its corresponding value from the dictionary, and the word is added to the seen set. Otherwise, the original word is used.
  • The code joins the list of words generated in the previous step using the join() method with a space separator to form the final string, and assigns the result to the res variable.
  • The code prints the final string using the print() function and string concatenation.

Python3




# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. Classes help understand better . '
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing replace mapping
repl_dict = {'Gfg': 'It', 'Classes': 'They'}
 
# Replace duplicate Occurrence in String
# Using set() + loop + list comprehension
words = test_str.split()
seen = set()
res = [repl_dict[word] if word in repl_dict and word not in seen and not seen.add(word) else word for word in words]
 
# join the list of words to form the final string
res = ' '.join(res)
 
# printing result
print("The string after replacing : " + str(res))
 
 
Output
The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .  The string after replacing : It is best . Gfg also has They now. Classes help understand better .

Time complexity: O(n), where n is the length of the input string. This is because we iterate over each word in the string exactly once.

Space complexity: O(n), where k is the number of keys in the replacement dictionary. This is because we use a set to store the words that have already been replaced.

Method #4: Using regular expressions

This method uses the re module to search for the repeated occurrences of the words in the string and replaces them with their corresponding values from the repl_dict.

step-by-step approach:

Import the re module.
Initialize the test_str and repl_dict variables.
Define a regular expression pattern to match repeated occurrences of the words in the repl_dict.
Use the re.sub() method to replace the matched patterns with their corresponding values from the repl_dict.
Print the original and replaced strings.

Python3




import re
 
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. \
                Classes help understand better . '
 
# initializing replace mapping
repl_dict = {'Gfg': 'It', 'Classes': 'They'}
 
# regular expression pattern to match repeated occurrences
pattern = r'\b(' + '|'.join(repl_dict.keys()) + r')\b(?=.*\b\1\b)'
 
# Replace duplicate Occurrence in String
res = re.sub(pattern, lambda match: repl_dict[match.group()], test_str)
 
# printing result
print("The original string is : " + str(test_str))
print("The string after replacing : " + str(res))
 
 
Output
The original string is : Gfg is best . Gfg also has Classes now.                 Classes help understand better .  The string after replacing : It is best . Gfg also has They now.                 Classes help understand better . 

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(1)



Next Article
Case insensitive string replacement in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Replace multiple occurrence of character by single
    Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character. Examples: Input : Geeksforgeeks, ch = 'e' Output : Geksforgeks Input : Wiiiin, ch = 'i' Output : WinReplace multiple occurrence of character by singleApproach #1 : Nai
    4 min read
  • Python | Replace duplicates in tuple
    Sometimes, while working with Python tuples, we can have a problem in which we need to remove tuples elements that occur more than one times and replace duplicas with some custom value. Let's discuss certain ways in which this task can be performed. Method #1 : Using set() + list comprehension The c
    5 min read
  • Python - Characters Index occurrences in String
    Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
    6 min read
  • Case insensitive string replacement in Python
    We are given a string and our task is to replace a specific word in it, ignoring the case of the letters. This means if we want to replace the word "best" with "good", then all variations like "BeSt", "BEST", or "Best" should also be replaced. For example, if the input is "gfg is BeSt", then the out
    3 min read
  • Python | Replace characters after K occurrences
    Sometimes, while working with Python strings, we can have a problem in which we need to perform replace of characters after certain repetitions of characters. This can have applications in many domains including day-day and competitive programming. Method #1: Using loop + string slicing This is brut
    5 min read
  • Python - Remove K length Duplicates from String
    To remove consecutive K-length duplicates from a string iterate through the string comparing each substring with the next and excluding duplicates. For example we are given a string s = "abcabcabcabc" we need to remove k length duplicate from the string so that the output should become "aaaabc" . We
    3 min read
  • Python - Replace Different Characters in String at Once
    The task is to replace multiple different characters in a string simultaneously based on a given mapping. For example, given the string: s = "hello world" and replacements = {'h': 'H', 'o': '0', 'd': 'D'} after replacing the specified characters, the result will be: "Hell0 w0rlD" Using str.translate
    3 min read
  • Python - All occurrences of substring in string
    A substring is a contiguous occurrence of characters within a string. Identifying all instances of a substring is important for verifying various tasks. In this article, we will check all occurrences of a substring in String. Using re.finditer()re.finditer() returns an iterator yielding match object
    3 min read
  • Python Program to Replace all Occurrences of ‘a’ with $ in a String
    Given a string, the task is to write a Python program to replace all occurrence of 'a' with $. Examples: Input: Ali has all aces Output: $li h$s $ll $ces Input: All Exams are over Output: $ll Ex$ms $re Over Method 1: uses splitting of the given specified string into a set of characters. An empty str
    3 min read
  • Python - Mid occurrence of K in string
    Given a String, the task is to write a Python program to extract the mid occurrence of a character. Input : test_str = "geeksforgeeks is best for all geeks", K = 'e' Output : 10 Explanation : 7 occurrences of e. The 4th occurrence [mid] is at 10th index. Input : test_str = "geeksforgeeks is best for
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences