Python 3.6 - 使用 JSON 的文字字符串插值
Python 3.6 - Literal string interpolation using JSON
我正在尝试读取一个 JSON 文件,其中包含 Python 个变量,这些变量应显示为变量的值而不是变量本身。
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.
由于格式字符串在变量中,因此您需要使用 format
方法而不是 f-strings
json_variable = 'Hello, I want to be there in {defined_days} days'
defined_days = 3
interpolated_text = json_variable.format(**locals())
print(interpolated_text)
输出:
Hello, I want to be there in 3 days
我正在尝试读取一个 JSON 文件,其中包含 Python 个变量,这些变量应显示为变量的值而不是变量本身。
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.
由于格式字符串在变量中,因此您需要使用 format
方法而不是 f-strings
json_variable = 'Hello, I want to be there in {defined_days} days'
defined_days = 3
interpolated_text = json_variable.format(**locals())
print(interpolated_text)
输出:
Hello, I want to be there in 3 days