Python - Replace duplicate Occurrence in String


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 for the same −

Example

 Live Demo

my_str = 'Jane is the best . Jane loves to cook. Jane and Will cook together'
print("The string is : ")
print(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("The string after replacing with values is : ")
print(my_result)

Output

The string is :
Jane is the best . Jane loves to cook. Jane and Will cook together
The string after replacing with values is :
Jane is the best . She loves to cook. She and Will cook together

Explanation

  • A string is defined, and is displayed on the console.
  • The dictionary with the help of which values need to be replaced is defined.
  • The keys of the dictionary are accessed, and are replaced with the specific values.
  • This operation’s data is assigned to a variable.
  • It is then displayed as output on the console.

Updated on: 11-Mar-2021

526 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements