find all possible combinations of letters in a string in python [duplicate]

Your example input/output suggests that you are looking for a power set. You could generate a power set for a string using itertools module in Python:

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

print(list(map(''.join, powerset('abcd'))))



Note: the output includes the empty string.

Leave a Comment