用python打印语句和json响应

用python打印语句和json响应,python,Python,我对python非常陌生,我查看了python文档,它们有一个print语句,看起来类似于C语言printf。然而,我试图模拟它,但它不起作用。我目前正在解析json响应,如果有人能帮助我,甚至给我一点提示,那就太好了。谢谢:这是我的python代码 print('the inventory is {inventory} \n the orderlevel is {orderlevel} \n the slots is {slots}' %'inventory' = jsonRespons

我对python非常陌生,我查看了python文档,它们有一个print语句,看起来类似于C语言printf。然而,我试图模拟它,但它不起作用。我目前正在解析json响应,如果有人能帮助我,甚至给我一点提示,那就太好了。谢谢:这是我的python代码

   print('the inventory is {inventory} \n the orderlevel is {orderlevel} \n the slots is {slots}' %'inventory' = jsonResponse['dsn']['inventory'],'orderlevel' = jsonResponse['dsn']['order_level'],'slots' =  jsonResponse['slots']);

您混合了旧的printf样式格式说明符和新的基于.format的格式说明符的语法。为可读性添加换行符以编写打印语句的正确新方法是:

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']
    )
)

如果您使用的是Python 3.6以后的版本,还可以使用Python中的tutorial link获得可读性非常好的代码,该代码使用了在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}')