'Delete a sequence of redundant 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 appears 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. Are there any alternatives for this problem ?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1