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

前端 未结 3 755
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 07:10

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

3条回答
  •  渐次进展
    2021-01-03 07:32

    You can use itertools.combinations here. You simply need to pick two splitting points to generate each resulting string:

    from itertools import combinations
    s = "thisisateststring"
    pools = range(1, len(s))
    res = [[s[:p], s[p:q], s[q:]] for p, q in combinations(pools, 2)]
    print res[0]
    print res[-1]
    

    Output:

    ['t', 'h', 'isisateststring']
    ['thisisateststri', 'n', 'g']
    

提交回复
热议问题