本文介绍了python字符串替换,生成所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用字符串,每个字符串都有一个动态数量的可选变量:

I work with strings, each having a dynamic amount of optional variables in parenthesis:

(?please) tell me something (?please)

现在我想用空字符串替换变量并取回所有可能的变量:

Now I want to replace the variables with an empty string and get back all possible variations:

tell me something (?please)

(?please) tell me something

tell me something

想要的功能应该处理多个,不同和无穷无尽变量数量。

The wanted function is supposed to handle multiple, different and an endless amount of variables.

任何帮助高度赞赏。

推荐答案

在中使用解决方案的问题是该解决方案迭代原始字符串中的每个字符,而你想检查原始字符串的子串。因此,你应该 split()你的字符串并迭代该列表。此外,当您最后加入列表时,请在单词之间放回空格。例如,

The problem with using the solution at String Replacement Combinations is that solution iterates over each character in the original string, whereas you want to check substrings of the original string. Thus, you should split() your string and iterate over that list. Also, when you join the list at the end, put the spaces back between the words. For example,

def filler(word, from_char, to_char):
    options = [(c,) if c != from_char else (from_char, to_char) for c in word.split(" ")]
    return (' '.join(o) for o in product(*options))
list(filler('(?please) tell me something (?please)', '(?please)', ''))

返回

['(?please) tell me something (?please)', '(?please) tell me something ', ' tell me something (?please)', ' tell me something ']

如果你想省略不包含删除的行(行'(?请)告诉我一些事情(?请)'),一个hacky解决方案就是删除结果的第一个元素,因为 product 的工作原理保证第一个结果选择每个选项的第一个元素,这对应于没有删除字符串的行。

If you want to omit the line that contains no removals ( the line '(?please) tell me something (?please)' ), a hacky solution is simply to remove the first element of the result, since the way product works guarantees the first result picks the first element of each option, which corresponds to the line that has no strings removed.

这篇关于python字符串替换,生成所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:24