查找从Python中的字符串中删除给定char的所有可能排列

时间:2019-02-21 11:41:37

标签: python python-3.x

我想要一个脚本,该脚本将通过删除给定句子的单词之间的任意数量的空格来生成所有可能的文本:

示例:

原文:

  

我要删除空格

预期输出:

I want to delete spaces

Iwant to delete spaces

Iwant todeletespaces

Iwanttodelete spaces

Iwanttodeletespaces
     

2 个答案:

答案 0 :(得分:2)

您可以使用itertools来做到这一点。

我们创建一个单词列表,然后将它们与''(空字符串)或' '(空格)的所有可能组合结合起来:

from itertools import product, zip_longest

s = 'I want to delete spaces'
words = s.split()

for separators in product((' ', ''), repeat=len(words)-1):
    print(''.join(word+separator for word, separator in zip_longest(words, separators, fillvalue='')))

输出:

I want to delete spaces
I want to deletespaces
I want todelete spaces
I want todeletespaces
I wantto delete spaces
I wantto deletespaces
I wanttodelete spaces
I wanttodeletespaces
Iwant to delete spaces
Iwant to deletespaces
Iwant todelete spaces
Iwant todeletespaces
Iwantto delete spaces
Iwantto deletespaces
Iwanttodelete spaces
Iwanttodeletespaces

由于单词多于分隔符,因此我们将zip_longestfillvalue=''结合使用,以便在最后一个单词之后使用空字符串作为分隔符。

答案 1 :(得分:0)

您可以使用find

s = 'I want delete spaces'
while ' ' in s:
    ind = s.find(' ')
    s = s[:ind] + s[ind+1:]
    print(s)

I want delete spaces
Iwant delete spaces
Iwantdelete spaces
Iwantdeletespaces

以此类推。