Search code examples
pythonstringcombinations

python/string: how to get all the possible combinations in string considering only space for splitting the string


I have a string dt = '301 302 303' how can I get different combinations of above string with considering only spaces while splitting the string.

# output
301
302
303
301 302
301 303
302 303
301 302 303

Solution

  • Please use itertools module turn the string to a list and then iterate

    dt = '301 302 303' 
    import itertools
    list1 = dt.split()
    for i in range(1,len(list1) + 1):
        for subset in itertools.combinations(list1,i):
            print(subset)
    

    output

    ('301',)
    ('302',)
    ('303',)
    ('301', '302')
    ('301', '303')
    ('302', '303')
    ('301', '302', '303')