3

我使用 python 2.6 并阅读了许多有关从“打印”中删除新行的链接,但找不到使用示例以及使用模符号 (%) 进行格式化的示例。在我的程序中,我试图在计算数据的循环行中编写,但每行数据来自不同的计算:

while 循环
    ... 计算 value1 和 value2
    打印 ('%10d %10s') % (value1, value2) [1]
    ... 计算 value3 和 value4
    打印 ('%7s %15d') % (value3, value4) [2]
    print #这是换行符的来源

所以我想得到:

值1 值2 值3 值4
价值5 价值6 价值7 价值8
...

基本上这种方法保持了我的程序的可读性(每条实线都有超过 20 个计算位置)。相反的方法是将所有数据连接成一个长字符串,但可能会丢失可读性。
是否可以使用 [1] 和 [2] 中的“print () % ()” 语法删除换行符?

4

3 回答 3

6

如果,在语句末尾添加逗号 ( ),则将省略换行符:

print ('%10d %10s') % (value1, value2),

http://docs.python.org/reference/simple_stmts.html#print

一个'\n'字符写在末尾,除非print语句以逗号结尾。如果语句仅包含关键字,则这是唯一的操作print

于 2012-08-07T09:45:04.613 回答
1
while loop
    ... calulating value1 and value2
    print '%10d %10s') % (value1, value2) , 
    ... calulating value3 and value4
    print ('%7s %15d') % (value3, value4) ,
    print #this is where newline should come from

注意,在最后prints

于 2012-08-07T09:45:43.530 回答
0

不使用prints 尾随逗号(或者,使用 Py3/关键字参数)的唯一方法from __future__ import print_functionend那么您必须一次完成所有打印 - 即:

while ...:
    # calulating value1 and value2
    # calulating value3 and value4
    print '%10d %10s %7s %15d' % (value1, value2, value3, value4)

如果这使可读性成为问题,请考虑将计算逻辑放入函数中,以便您可以执行以下操作:

while ...:
    value1 = calculate_value1()
    value2 = calculate_value2()
    value3 = calculate_value3()
    value4 = calculate_value4()
    print '%10d %10s %7s %15d' % (value1, value2, value3, value4)
于 2012-08-07T10:02:22.537 回答