- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements