sgp
sgp

Reputation: 1778

Python 3 How to find the different combinations of a String

Given a String is there any short way in Python 3 to find the different combinations of the space seperated words in that string ?

For eg:

If the input string is 'Peaches Apples Bananas', I want output as:

'Peaches Apples Bananas'

'Peaches Bananas Apples'

'Apples Bananas Peaches'

'Apples Peaches Bananas'

'Bananas Peaches Apples'

'Bananas Apples Peaches'

Upvotes: 0

Views: 211

Answers (2)

A. Rodas
A. Rodas

Reputation: 20689

I think you are looking for itertools.permutations:

import itertools

for perm in itertools.permutations('Peaches Apples Bananas'.split(' ')):
    print(' '.join(perm))

Upvotes: 1

RodericDay
RodericDay

Reputation: 1292

import itertools

string = 'Peaches Apples Bananas'
word_list = string.split(' ')

output = [' '.join(permutation) for permutation in itertools.permutations(word_list)]

Upvotes: 1

Related Questions