简体   繁体   English

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

[英]Find all possible permutations of removing given char from a string in Python

I want a script that will generate all possible texts by deleting any number of spaces between words of a given sentence: 我想要一个脚本,该脚本将通过删除给定句子的单词之间的任意数量的空格来生成所有可能的文本:

Example: 例:

Original sentence: 原句:

I want to delete spaces 我想删除空格

Expected output: 预期产量:

 I want to delete spaces Iwant to delete spaces Iwant todeletespaces Iwanttodelete spaces Iwanttodeletespaces 

etc. 等等

You can do it using itertools . 您可以使用itertools完成

We create a list of words, then join them with all possible combinations of '' (empty string) or ' ' (space): 我们创建一个单词列表,然后将它们与'' (空字符串)或' ' (空格)的所有可能组合结合起来:

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='')))

Output: 输出:

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

As there is one more word than separators, we use zip_longest with a fillvalue='' in order to have an empty string as separator after the last word. 因为单词比分隔符多,所以我们使用zip_longestfillvalue='' ,以便在最后一个单词之后使用空字符串作为分隔符。

You can use find : 您可以使用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

and so on. 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM