Given a string taken from the following set:
strings = [ "The sky is blue and I like it", "The tree is green and I love it", "A lemon is yellow" ]
I would like to constuct a function which replaces subject, color and optional verb from this string with others values.
All strings match a certain regex pattern as follow:
regex = r"(?:The|A) (?P<subject>\w+) is (?P<color>\w+)(?: and I (?P<verb>\w+) it)?"
The expected output of such function would look like this:
repl("The sea is blue", "moon", "white", "hate") # => "The moon is white"
Here is the solution I come with (I can't use
.replace() because there is edge cases if the string contains the subject twice for example):
def repl(sentence, subject, color, verb): m = re.match(regex, sentence) s = sentence new_string = s[:m.start("subject")] + subject + s[m.end("subject"):m.start("color")] + color if m.group("verb") is None: new_string += s[m.end("color"):] else: new_string += s[m.end("color"):m.start("verb")] + verb + s[m.end("verb"):] return new_string
Do you think there is a more straightforward way to implement this?