How to Replace Duplicate Occurrences in a String Using Python

In this tutorial, we’ll learn how to program "How to Replace Duplicate Occurrences in a String Using Python." The objective is to efficiently replace duplicate occurrences in a string. This tutorial will guide you through the process step by step, helping you detect any duplicate occurrences of words in a string and replace them with a specific word. So, let’s get started!

This topic is straightforward to understand. Just follow the instructions I provide, and you’ll complete it with ease. The program I’ll demonstrate will show you the correct and efficient way to check whether duplicate words are present in a string and replace them with a specific word. So, let’s dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. while True:
  2.     print("\n============= Replace Duplicate Occurrences in a String =============\n")
  3.  
  4.     my_str = 'I love programming. I working code'
  5.  
  6.  
  7.     print("Current string: " + str(my_str))
  8.  
  9.  
  10.     repl_dict = {'I' : 'Me'}
  11.  
  12.  
  13.     my_list = my_str.split(' ')
  14.     res = ' '.join([repl_dict.get(val) if val in repl_dict.keys() and my_list.index(val) != idx
  15.                                                                 else val for idx, val in enumerate(my_list)])
  16.  
  17.  
  18.     print("New String: " + str(res))
  19.  
  20.     opt = input("\nDo you want to try again?(yes/no): ")
  21.        
  22.     if opt.lower() == 'yes':
  23.         ret=False
  24.     elif opt.lower() == 'no':
  25.         ret=True
  26.         print("Exiting program....")
  27.     else:
  28.         print("Please enter yes/no:")
  29.         break
  30.  
  31.     if ret == False:
  32.         continue

This program replaces duplicate occurrences of specific words in a string, but keeps the first instance unchanged. It uses a dictionary (repl_dict) to define replacements and processes the string by splitting it into words, then reconstructing it while swapping only the duplicates. It keeps running until the user decides to exit.

Output:

There you have it we successfully created How to Replace Duplicate Occurrences in a String Using Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment