Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *