python string replacement, generating all possible combinations

泪湿孤枕 提交于 2019-12-11 19:25:12

问题


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.

any help highly appreciated.


回答1:


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

This returns

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

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.



来源:https://stackoverflow.com/questions/31497084/python-string-replacement-generating-all-possible-combinations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!