在各行上格式化打印输出?

时间:2016-08-31 00:59:57

标签: python python-3.x printing formatting

我正在尝试格式化查询的结果,以便将结果打印在各自的行上。例如,我按商店编号查询商店并从JSON文件获取位置,但在打印时,商店编号和位置在不同的行上打印:

代码段:(搜索商店35和96)

for store, data in results.items():
    print('Store: {}'.format(store))
    if data:
        for location in data:
            print(location)

当前输出:
店铺:35
{'location':爱荷华州}
店铺:96
{'location':明尼苏达州}

所需的输出(或类似的东西):
店铺:35,'位置':爱荷华州 商店:96,'location':明尼苏达州

2 个答案:

答案 0 :(得分:1)

在第一个print语句中添加end=''可以解决问题。通过指定结束字符是空字符串,您将覆盖默认的\n字符(默认情况下,print语句以新行字符结尾)。

for store, data in results.items():
    print('Store: {}'.format(store), end='')
    if data:
        for location in data:
            print(location)

我们只会将end=''添加到第一个print语句中,因为我们希望在您打印出该位置后打印新行。

如果您想用,分隔打印件,您只需将+ ','添加到第一张打印声明中。

如果您正在使用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

正如您所看到的,每一行都以新行字符结束,这会为每个语句打印一个新行。

答案 1 :(得分:0)

我会将所有输出写入变量并在结尾处仅打印一次变量。这也允许您节省时间(尽管使用更多内存),因为您只需要一次访问stdout。代码也更容易遵循(在我看来):

output = ''
for store, data in results.items():
    output += 'Store: {}'.format(store)
    if data:
        for location in data:
            output += location+'\n'

# Only at the end you print your output
print(output)

您还可以在每次迭代结束时打印(您仍然可以访问stdout一半次):

for store, data in results.items():
    output = 'Store: {}'.format(store)
    if data:
        for location in data:
            output += location+'\n'

    # Print only at the end of the loop
    print(output)

如果您想为每个商店添加新行,但不是每个"位置"

output = ''
for store, data in results.items():
    output += 'Store: {}'.format(store)
    if data:
        for location in data:
            output += location
        output += '\n'

# Only at the end you print your output
print(output)

我认为这种方法更灵活,更易于在代码中阅读,而且速度更快。

希望有所帮助

相关问题