0

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.

HTron
  • 337
  • 3
  • 14
  • I have tried the code from DSM http://stackoverflow.com/questions/14841652/string-replacement-combinations but it doesn't work on a full sentence, don't know why. – HTron Jul 19 '15 at 01:21

1 Answers1

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.

Community
  • 1
  • 1
James
  • 1,198
  • 8
  • 14
  • sorry one more question: how can I do it with several, different and optional variables. iterating in a loop doesn't work for me – HTron Jul 19 '15 at 03:59
  • You will need to modify `c != from_char` to make it compare against a list of variables. Please give it a try, and let me know how it goes. – James Jul 19 '15 at 04:36
  • you made me do it! `options = [(c,) if c not in from_char else (c, to_char) for c in word.split(" ")] ` thank you – HTron Jul 19 '15 at 10:10