python中的打印语句以及json响应

时间:2018-09-11 23:35:35

标签: python

我是python的新手,我看了看python文档,他们有一个打印语句here,看起来类似于C语言printf。但是,我尝试对其进行仿真,但没有成功。我目前正在解析json响应,如果有人可以帮助我甚至是一点暗示,那将很棒。谢谢:这是我的python代码。

from_json

2 个答案:

答案 0 :(得分:2)

您正在混合使用旧的printf样式格式说明符和新的基于.format()的格式说明符。编写print语句(添加换行符以提高可读性)的正确(新)方法是:

print(
    'the inventory is {inventory} \n'
    ' the orderlevel is {orderlevel} \n'
    ' the slots is {slots}'
    .format(
        # Note that quotes around keyword arguments aren't allowed.
        inventory = jsonResponse['dsn']['inventory'],
        orderlevel = jsonResponse['dsn']['order_level'],
        slots =  jsonResponse['slots']
    )
)

答案 1 :(得分:0)

如果您使用的是Python 3.6及更高版本,则还可以在Python中使用f strings(教程链接)来获得一个非常好读的代码,该代码使用从print语句声明的变量:

#Declare your variables like you normally would
inventory = jsonResponse['dsn']['inventory']
orderlevel = jsonResponse['dsn']['order_level']
slots =  jsonResponse['slots']

#print with an `f` at the beginning of your string
print(f'the inventory is {inventory}\n the orderlevel is {orderlevel}\n the slots is {slots}')