Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete a sequence of redandant letters in Python

i want to be able to delete a sequence of repeated letters in a word in python .Let’s say the word is "helllllllo" , i want to be able to delete the repeated letter which appear more than twice .The only solution i found was a nested loop but in terms of performance especially when the dataset is large , it can get quite heavy. Any altrnatives for this problem ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s a way to do it:

s = 'helllllloolloolloollolo'
t = ''.join(c for i, c in enumerate(s) if i < 2 or not(c == s[i-1] and c == s[i-2]))
print(t)

Output:

helloolloolloollolo

The argument to join is a comprehension that filters out characters in s that are the same as the two preceding characters. Then join turns the resulting sequence into a string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading