Group i consecutive identical character in a string into a list

Viewed 1179

I want the input string to be separated in such a way that all the consecutive identical characters are grouped together in a list.

Example1:

str : aabbcccdeddgg

output: ['aa', 'bb', 'ccc', 'd', 'e', 'dd']

Desired Output : ['aa', 'bb', 'ccc', 'd', 'e', 'dd', 'gg']

Example2:

str : helloop

output: ['h', 'e', 'll', 'oo'] Desired Output : ['h','e','ll','oo','p']

On using the below code:

s = input()
li = []
temp_li = []
grp = s[0]
for ch in s[1:]:
    if ch== grp[-1]:
        grp+=ch
    else:
        li.append(grp)

        grp = ch
print(li)

note: Program is not showing output for the last set of identical characters

Expected Answers from community:

  • Modification on above program to show the correct output
  • or better solution in general
2 Answers
from itertools import groupby
x = "aabbcccdeddgg"
[''.join(g) for _, g in groupby(x)]

>> ['aa', 'bb', 'ccc', 'd', 'e', 'dd', 'gg']

You need to put li.append(grp) outside the for loop to include the last group matched:

for ch in s[1:]:
  if ch== grp[-1]:
    grp+=ch
  else:
    li.append(grp)
    grp = ch

li.append(grp) #account for last instance of grp

Output (for s='helloop'):

['l', 'e', 'll', 'oo', 'p']
Related