python string replacement, generating all possible

2019-08-25 14:20发布

问题:

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.