【问题标题】:how to print a string who contains variables, the string is contained is .json file? [closed]如何打印包含变量的字符串,该字符串包含的是.json文件? [关闭]
【发布时间】:2021-04-03 11:52:38
【问题描述】:

你好

我有一个小问题,我无法解决它

我尝试打印一个包含变量的字符串,这个字符串也包含在一个字符串中。

像这样:

import json

with open('example.json','r') as f:
   json_content = json.load(f)

variable = 'var'
message = json_content['message']

print(message) 

example.json

{'message': 'this is a message with a {variable}'}

我想得到输出“这是一条带 var 的消息”

对不起,如果不是很清楚,我是法国人^^'

【问题讨论】:

  • 欢迎来到 StackOverflow!你能告诉我们你到目前为止所做的尝试吗?
  • “我尝试打印一个包含变量的字符串,这个字符串也包含在一个字符串中。”这不是对您要实现的目标的非常清楚的描述,您想在消息(另一个字符串)的给定位置添加名为“变量”的字符串变量,对吗? @DeepSpace 所说的也适用。
  • json_content[message]这里的变量message是在赋值前引用的。
  • JSON 文件应如下所示:{"message":"this is a message with a {variable}"}

标签: python json python-3.x string substring


【解决方案1】:

我认为您应该更多地发展您的基础知识,并且在此处提问之前尝试自己的代码

我猜你想要达到的目标可以这样完成。

import json

with open("example.json", "r") as f:
   json_content = json.load(f)

message = json_content["message"]
variable = "var"
print(message.format(variable=variable))

# prints
# this is a message with a var

【讨论】:

    猜你喜欢
    • 2018-12-27
    • 2017-11-17
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2022-11-27
    • 1970-01-01
    相关资源
    最近更新 更多