Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Join String to Produce Combinations For All Words in String

If my string is this: 'this is a string', how can I produce all possible combinations by joining each word with its neighboring word?

What this output would look like:

this is a string
thisis a string
thisisa string
thisisastring
thisis astring
this isa string
this isastring
this is astring

What I have tried:

s = 'this is a string'.split()    
for i, l in enumerate(s):
        ''.join(s[0:i])+' '.join(s[i:])

This produces:

'this is a string'
'thisis a string'
'thisisa string'
'thisisastring'

I realize I need to change the s[0:i] part because it's statically anchored at 0 but I don't know how to move to the next word is while still including this in the output.

like image 991
Jarad Avatar asked Feb 18 '26 17:02

Jarad


2 Answers

A simpler (and 3x faster than the accepted answer) way to use itertools product:

s = 'this is a string'
s2 = s.replace('%', '%%').replace(' ', '%s')
for i in itertools.product((' ', ''), repeat=s.count(' ')):
    print(s2 % i)
like image 75
panda-34 Avatar answered Feb 20 '26 20:02

panda-34


You can also use itertools.product():

import itertools

s = 'this is a string'

words = s.split()
for t in itertools.product(range(len('01')), repeat=len(words)-1):
    print(''.join([words[i]+t[i]*' ' for i in range(len(t))])+words[-1])
like image 22
tommy.carstensen Avatar answered Feb 20 '26 22:02

tommy.carstensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!