如果您想将多个变量“替换”到字符串中,并明确指出您要实例化什么而不在.format() 中输入许多参数:
- 创建字典。键应该是要在获取的字符串中替换的字符串,值应该是代替键出现的变量。
- 使用双星号
** 从 namespace 字典中提取键以将字典“解包”到 .format() 参数列表中,以用获取的字符串中的值替换键
根据你的例子:
import json
a = 'greet'
name = 'John'
weight = 80
height = 190
age = 23
# 1.
namespace = {'name': name, 'age': age, 'weight': weight, 'height': height}
json_dict_all_keys = json.loads('{"greet" : "Hello! {name}, {age} years old, {height}cm, {weight}kg. How are you?"}')
json_dict_some_keys = json.loads('{"greet" : "Hello! {name}, {weight}kg. How are you?"}')
json_dict_mixed_keys = json.loads('{"greet" : "Hello! {name}, {other} years old, {key}cm, {weight}kg. How are you?"}')
json_dict_none_of_keys = json.loads('{"greet" : "Hello! {some}, {other} years old, {key}cm, {here}kg. How are you?"}')
if a in json_dict:
# 2.
print(json_dict_all_keys[a].format(**namespace)) # Hello! John, 23 years old, 190cm, 80kg. How are you?
print(json_dict_some_keys[a].format(**namespace)) # Hello! John, 80kg. How are you?
print(json_dict_mixed_keys[a].format(**namespace)) # Raising KeyError!
print(json_dict_none_of_keys[a].format(**namespace)) # Raising KeyError too!
如您所见,不需要使用来自namespace 的所有“密钥”。
但要小心 - 当您要格式化的字符串中出现 namespace 中未包含的“key”时,会发生 KeyError。
为了简化解释,我使用了json.loads,而不是使用json.load从文件中加载json。