我正在尝试格式化查询结果,以便将结果打印在各自的行上。例如,我按商店编号查询商店并从 JSON 文件获取位置,但在打印时,商店编号和位置打印在单独的行上:
代码片段:(搜索商店 35 和 96)
for store, data in results.items():
print('Store: {}'.format(store))
if data:
for location in data:
print(location)
当前输出:
店铺:35
{'位置':爱荷华州}
店铺:96
{'位置':明尼苏达州}
期望的输出(或类似的东西):
商店:35,“位置”:爱荷华州
商店:96,“位置”:明尼苏达州
最佳答案
将 end=''
添加到您的第一个打印语句中应该可以解决该问题。通过指定结束字符为空字符串,您将覆盖默认的 \n
字符(默认情况下,打印语句以换行符结束)。
for store, data in results.items():
print('Store: {}'.format(store), end='')
if data:
for location in data:
print(location)
我们只会将 end=''
添加到第一个打印语句中,因为我们希望在打印出位置后打印新行。
如果您想用 ,
分隔打印,当然您只需将 + ','
添加到您的第一个打印语句中即可。
如果您使用的是 Python 3,这将立即起作用。如果您使用的是 Python 2.X,则必须将此行添加到文件顶部:from __future__ import print_function
这是一个简单的实际例子:
from __future__ import print_function
l1 = ['hello1', 'hello2', 'hello3']
l2 = ['world1', 'world2', 'world3']
for i,j in zip(l1, l2):
print (i, end='')
print (j)
Output:
hello1world1
hello2world2
hello3world3
如果我们采用相同的代码,但稍作修改并删除 end=''
,将会发生以下情况:
from __future__ import print_function
l1 = ['hello1', 'hello2', 'hello3']
l2 = ['world1', 'world2', 'world3']
for i,j in zip(l1, l2):
print (i)
print (j)
Output:
hello1
world1
hello2
world2
hello3
world3
正如您所看到的,每一行都会以换行符结尾,这会为每个语句打印一个新行。
关于python - 格式化各行打印的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39239203/