简体   繁体   English

Python如何根据dict或json对象格式化字符串?

[英]Python how to format a string based on dict or json object?

I have a JSON file which I converted to a Dict that has something like我有一个 JSON 文件,我将其转换为具有类似内容的 Dict

{
  "a": "1",
  "b": "2",
  "c": "3"
}

and I want to format this string based on that JSON我想根据那个 JSON 格式化这个字符串

"Blah {a} Blah Blah {b} {c}"

to output输出

"Blah 1 Blah Blah 2 3"

I haven't tried anything and I couldn't find anything by Googling it ( Python how to format string based on json ), most results were just to pretty print JSON.我没有尝试过任何东西,也没有通过谷歌搜索找到任何东西( Python how to format string based on json ),大多数结果只是为了漂亮地打印 JSON。

You can use str.format to easily accomplish this.您可以使用str.format轻松完成此操作。 Assuming you've loaded you JSON data in memory as a dictionary:假设您已将 JSON 数据作为字典加载到内存中:

>>> data = {
  "a": "1",
  "b": "2",
  "c": "3"
}
>>> "Blah {a} Blah Blah {b} {c}".format(**data)
'Blah 1 Blah Blah 2 3'

if you're not sure how to load your JSON string into memory, use json.loads :如果您不确定如何将 JSON 字符串加载到内存中,请使用json.loads

>>> from json import loads
>>> data = loads('{ "a": "1", "b": "2", "c": "3" }')
>>> data
{'a': '1', 'b': '2', 'c': '3'}

So, put together, the complete script would be:因此,放在一起,完整的脚本将是:

from json import loads
data = loads('{ "a": "1", "b": "2", "c": "3" }')
print("Blah {a} Blah Blah {b} {c}".format(**data))

if you have the JSON array as a variable in your code like below如果您的代码中有 JSON 数组作为变量,如下所示

data = {
  "a": "1",
  "b": "2",
  "c": "3"
}

You can then call those individual items based on the key name in the key/value pairs as defined in the data variable.然后,您可以根据 data 变量中定义的键/值对中的键名称调用这些单独的项目。

It can then be as simple as然后它可以很简单

new_string = "Blah " + str(data["a"]) + " blah blah " + str(data["b"]) + " " + str(data["c"])

The variable new_string will then be "Blah 1 blah blah 2 3"变量 new_string 将是“Blah 1 blah blah 2 3”

I used the str() method just in case what was in the JSON array is not a string already.我使用了 str() 方法,以防万一 JSON 数组中的内容已经不是字符串。

If you are trying to be more programmatic about it, and the string will be generated many times with different data sets, you could do it similar to this, but with variable names that are meaningful to you and your project and made into a function.如果您想对其进行更多编程,并且将使用不同的数据集多次生成字符串,您可以执行与此类似的操作,但使用对您和您的项目有意义的变量名称并制作成一个函数。

data = {"a": "1", "b": "2", "c": "3"}
var_0 = str(data["a"])
var_1 = str(data["b"])
var_2 = str(data["c"])
new_string = "Blah " + var_0 + " blah blah " + var_1 + var_2

Then from there you can do whatever you need with the new_string然后从那里你可以用 new_string 做任何你需要的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM