user3507230 user3507230 - 7 months ago 18
Python Question

Return all possible combinations of a string when splitted into n strings

I made a search for stackoverflow about this but couldn't find a way to do it. It probably involves itertools.

I want to find all the possible results of splitting a string, say the string

thisisateststring
into
n
(equal or unequal length, doesn't matter, both should be included) strings.

For example let
n
be
3
:

[["thisisat", "eststrin", "g"], ["th", "isisates", "tstring"], ............]

Answer

Including empty strings in your results will be rather awkward with itertools.combinations(). It's probably easiest to write your own recursive version:

def partitions(s, k):
    if not k:
        yield [s]
        return
    for i in range(len(s) + 1):
        for tail in partitions(s[i:], k - 1):
            yield [s[:i]] + tail

This will work for any number k of desired partitions for any string s.