user3507230 - 1 year ago 55

Python Question

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`

`n`

For example let

`n`

`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`

.

Source (Stackoverflow)