python - 可选的多行字符串替换
问题描述
我有一个长字符串,其中包含一些占位符,例如%name%
应该用字典给出的值替换。根据这个链接,我能够解决它。但是,如果另一个参数为 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)
解决方案
推荐阅读
- angular - 使用 Validators.required True 的正确方法是什么?
- c# - ASP.NET WebAPI 方法只能在本地工作,但不能在 WebServer 上工作
- ios - 在 UIAlertController 中点击“确定”操作时如何关闭呈现视图控制器
- android-studio - Android Firebase 云功能-使用邮箱删除用户
- objective-c - AVAudioEngine 在 iOS14 中获取 inputNode 属性崩溃
- java - Gradle 没有正确构建类名
- python-3.x - 如何在强制 Lambda 函数运行两次的 AWS Lambda 中强制打印异常和错误?
- r - 在函数调用内部构造的 glms 上的 step/stepAIC
- android - 谷歌移动视觉 api - 将面部裁剪为来自相机的位图
- python - MacOS Big Sur - Python ctypes find_library 找不到库(ssl、CoreFoundation 等