【问题标题】:Python 3.6 - Literal string interpolation using JSONPython 3.6 - 使用 JSON 的文字字符串插值
【发布时间】: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

【问题讨论】:

标签: python python-3.6 string-interpolation


【解决方案1】:

由于您的格式字符串在变量中,因此您需要使用 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

【讨论】:

  • 我不知道 **locals() 在 Python 中的确切含义(尤其是两个星号),但它确实有效。非常感谢。
  • locals() 返回调用时可用的所有局部变量及其值的dictionary** 用于将该字典展开为键值对以调用format。其中一个键值对将是defined_days=3。该 w 将被格式化字符串拾取以获得您想要的结果。当您有很多变量要传递给 format 时,这会更有用 - 您不必手动传递每个变量
  • 这是我读过的关于一切的最好解释。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 2022-07-01
  • 2018-06-29
  • 1970-01-01
  • 2011-04-29
相关资源
最近更新 更多