Python combinations of text given substring and arbitrary replacement
I have a string:
"foo bar foo foo"
And given a substring in that string, for example: "foo"
I want to get every combination substituting that "foo"
for some arbitrary string (it might have different length).
For example:
>>> combinations("foo bar foo foo", "foo", "fooer")
{
"foo bar foo foo",
"fooer bar foo foo",
"foo bar fooer foo",
"foo bar foo fooer",
"fooer bar fooer foo",
"fooer bar foo fooer",
"fooer bar fooer fooer",
"foo bar fooer fooer",
}
I have searched already and I can't find anything that could help me.
I know I have to use itertools.product
for the combinations, however I get stuck when there are more than one appearances in the same string and the substring and its substitution have different lengths.
By the moment I get the indices where I have to start replacing:
def indices_substring(a_str, sub):
"""https://stackoverflow.com/a/4665027/9288003"""
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub) # use start += 1 to find overlapping matches