1

I have a number string like below.

s = "1123433364433"

I'd like to get the result list of splited continuous same value like this. You can't change the location of the original each digit.

result = ["11", "2", "3", "4", "333", "6", "44", "33"]

What should be the easiest way to get this?

cloudrain21
  • 581
  • 4
  • 16

2 Answers2

6

Use itertools.groupby:

from itertools import groupby
s = "1123433364433"
print([''.join(i) for _, i in groupby(s)])

This outputs:

['11', '2', '3', '4', '333', '6', '44', '33']
blhsing
  • 77,832
  • 6
  • 59
  • 90
1

You can use module re for that as well:

import re
s = "1123433364433"
print([v[0] for v in re.finditer(r'(.)\1*', s)])

Outputs:

['11', '2', '3', '4', '333', '6', '44', '33']
Andrej Kesely
  • 118,151
  • 13
  • 38
  • 75