python字符串替换,生成所有可能的组合

编程入门 行业动态 更新时间:2024-10-08 19:49:33
本文介绍了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字符串替换,生成所有可能的组合

本文发布于:2023-11-30 07:30:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649176.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   字符串   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!