如果我的字符串是这样的:'this is a string'
,我如何通过将每个单词与其相邻单词连接来产生所有可能的组合?
这个输出会是什么样子:
this is a string
thisis a string
thisisa string
thisisastring
thisis astring
this isa string
this isastring
this is astring
我尝试过的:
s = 'this is a string'.split()
for i, l in enumerate(s):
''.join(s[0:i])+' '.join(s[i:])
这会产生:
'this is a string'
'thisis a string'
'thisisa string'
'thisisastring'
我意识到我需要更改 s[0:i]
部分,因为它静态锚定在 0 但我不知道如何移动到下一个单词 is
同时仍然在输出中包含 this
。
最佳答案
使用 itertools 产品的更简单(比公认答案快 3 倍)的方法:
s = 'this is a string'
s2 = s.replace('%', '%%').replace(' ', '%s')
for i in itertools.product((' ', ''), repeat=s.count(' ')):
print(s2 % i)
关于string - Python 连接字符串以生成字符串中所有单词的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29739011/