-1

I have a string like Hiiiiiiiiiiii which it may be contains a chain of a char in it, here i which it is repeated more than one times.I want to replace this chain of is with one i and get the Hi as the output.and for another example with the given word eeeeeeemadeeefghddd i want to get emadefghd as the output.How can I do this in python?

3 Answers3

5

You can use itertools here

>>> import itertools
>>> s = "Hiiiiiiiiiiii"
>>> ''.join(i for i, _ in itertools.groupby(s))
'Hi'

>>> s = 'eeeeeeemadeeefghddd'
>>> ''.join(i for i, _ in itertools.groupby(s))
'emadefghd'
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
3

You can replace every repetition of a character with the character itself using a fairly simple regex.

>>> import re
>>> re.sub(r'(.)\1+', r'\1', 'Hiiiiiiiiiiii')
'Hi'
>>> re.sub(r'(.)\1+', r'\1', 'eeeeeeemadeeefghddd')
'emadefghd'
timgeb
  • 76,762
  • 20
  • 123
  • 145
2

You can loop through the string using enumerate() and check each character against the one before it, for example:

s = 'eeeeeeemadeeefghddd'
result = ''
for i, c in enumerate(s):
    if i == 0:
        result += c
    else:
        if c != s[i-1]:
            result += c
print result

Output:

emadefghd
Mohd
  • 5,523
  • 7
  • 19
  • 30