N
N
Nurdaulet Maksutov2021-02-22 20:46:30
Python
Nurdaulet Maksutov, 2021-02-22 20:46:30

Split string by character sequence?

How to split a string by the sequence of characters that are in it. It would be better if short and productive.

INPUT: 111222555666644
OUTPUT: ['111', '222', '555', '6666', '44']

INPUT: aa11bbbccc
OUTPUT: ['aa', '11', 'bbb', 'ccc']

INPUT: aaaabbbbaaaabbbb
OUTPUT: ['aaaa', 'bbbb', 'aaaa', 'bbbb']

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aRegius, 2021-02-22
@maksutovn

from itertools import groupby

[''.join(items) for _, items in groupby(input_string)]

S
Sergey Karbivnichy, 2021-02-22
@hottabxp

Perhaps there is a one-liner in Python that solves your problem - I don't know. The first thing that came to mind:

my_list = list('111222555666644')
new_list = []
my_set = set(my_list)

for x in my_set:
  count_ = my_list.count(x)
  new_list.append(x*count_)

print(new_list)
# ['6666', '555', '222', '111', '44']
# ['aa', 'bbb', 'ccc', '11']

True, the sequence has gone astray, but I think it can be subdued.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question