我有一个带有一些占位符的长字符串,比如%name%
,应该用dict给定的值来替换。根据this链接,我能够解决它。但是,如果另一个参数为True,则某些部分只应包含在返回的字符串中。例如,使用此格式:
>>optional:This should only get printed, if 'optional' is True<<
我可能会让它工作,但我无法创建一个同样适用于多行的正则表达式
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)
根据预期产出:
My name is John.
I want to eat some Apples.
(in two lines)
目前没有回答
相关问题 更多 >
编程相关推荐