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
  • 649
  • 5
  • 17

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
  • 91,368
  • 6
  • 71
  • 106
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
  • 168,389
  • 15
  • 48
  • 91