使用带有 Yaml 文件的 Python f 字符串? [英] Leverage Python f-strings with Yaml files?
问题描述
如果我有一个 yaml 文件,其中包含一个带有括号符号 {} 的字符串,与 python f-strings 一起使用,这里如何利用 f-string 插值?以这个简单的 yaml 文件为例:
If I have a yaml file containing a string with the bracket notation {} used in partnership with python f-strings, how might a leverage the f-string interpolation here? Take for example this simple yaml file:
# tmp.yaml
k1: val1
k2: val2 as well as {x}
如果x = 'val3'
,我希望k2的值反映val2以及val3
If x = 'val3'
, I would like the value of the k2 to reflect val2 as well as val3
# app.py
x = 'val3'
with open('tmp.yaml', 'rt') as f:
conf = yaml.safe_load(f)
print(conf)
{'k1': 'val1', 'k2': 'val2 as well as {x}'}
这可以用格式字符串很容易地完成...
This could be accomplished pretty easily with format strings...
print(conf['k2'].format(x=x))
val2 as well as val3
但是如何对 f-strings 做同样的事情?
But how to do the same with f-strings?
推荐答案
您可以定义自定义构造函数:
You can define a custom constructor:
import yaml
values = { 'x': 'val3' }
def format_constructor(loader, node):
return loader.construct_scalar(node).format(**values)
yaml.SafeLoader.add_constructor(u'!format', format_constructor)
conf = yaml.safe_load("""
k1: val1
k2: !format val2 as well as {x}
""")
print(conf)
如果不想使用标签 !format
,也可以使用 add_constructor
和 u'tag:yaml.org,2002:str'
作为标签.这将使用您的默认字符串构造函数覆盖.
If you don't want to use the tag !format
, you can also use add_constructor
with u'tag:yaml.org,2002:str'
as tag. This will override the default string constructor with yours.
这篇关于使用带有 Yaml 文件的 Python f 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!