Menu Close

How to find all possible permutations of a given string in Python?

Sometimes, we want to find all possible permutations of a given string in Python.

In this article, we’ll look at how to find all possible permutations of a given string in Python.

How to find all possible permutations of a given string in Python?

To find all possible permutations of a given string in Python, we can use the itertools‘s permutation function.

For instance, we write

from itertools import permutations
perms = [''.join(p) for p in permutations('foobar')]

to call permutation with 'foobar' to find all permutations of the characters in the 'foobar' string.

We call ''.join with the permuted characters to join them back into strings.

Conclusion

To find all possible permutations of a given string in Python, we can use the itertools‘s permutation function.

Posted in Python, Python Answers