【发布时间】:2020-03-25 22:49:31
【问题描述】:
我正在尝试读取包含 Python 变量的 JSON 文件,该文件应显示为变量的值,而不是变量本身。
with open('path_to_file.json') as f:
my_json = json.load(f)
json_variable = my_json['text']
# The example text in the json file is:
# Hello, I want to be there in {defined_days} days
defined_days = 3
# What I tried, but doesn't work
interpolated_text = f'{json_variable}'
# Output of interpolated_text:
# Hello, I want to be there in {defined_days} days
它显示了来自 json 文件的字符串,但 defined_days 不会被替换为数字 3。
【问题讨论】:
-
试试
json_variable.format(defined_days=defined_days),f-strings 不是这样工作的。 -
请分享一些示例输入和输出,见How to Ask,minimal reproducible example。
标签: python python-3.6 string-interpolation