简体   繁体   中英

python string replacement, generating all possible combinations

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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