0

I have a long string with some placeholders like %name% which should be substituted with a value given by a dict. According to this link, I was able to solve it. Some parts however should only be included in the returned string, if another parameter is True. For example with this formatting:

>>optional:This should only get printed, if 'optional' is True<<

I might get it to work, but I was not able to create a regex expression that works also with multiline

import re 

# This works (https://stackoverflow.com/questions/26844742/advanced-string-replacements-in-python)
def replaceParameter(string, replacements):
  return re.sub('%(\w+)%', lambda m: replacements[m.group(1)], string)

# This does not work
def replaceOptionalText(myString, replacements):
  occurences = re.findall(">>(.*?):(.*)<<", myString, re.MULTILINE)
  # ... #

myLongString = r"""My name is %name%.
I want to >>eat:eat some %food%.
(in two lines)<<
>>drink:drink something<<
"""

replacements = {
  'name': 'John',
  'eat': True,
  'food': 'Apples',
  'drink': False,
}

myLongString = replaceOptionalText(myLongString, replacements)
myLongString = replaceParameter(myLongString, replacements)
print(myLongString)

with the expected Output:

My name is John.
I want to eat some Apples.
(in two lines)
Wulle
  • 153
  • 4

0 Answers0