2012-08-07 86 views
3

我使用python 2.6并阅读了很多关于从'print'中删除新行的链接,但找不到使用模数标志(%)格式化的用法示例。在我的计划,我想在计算数据的环行写的,但每一行数据来自不同的计算:python 2.6 print with formatting(%):remove newline

 
while loop 
    ... calulating value1 and value2 
    print ('%10d %10s') % (value1, value2) [1] 
    ... calulating value3 and value4 
    print ('%7s %15d') % (value3, value4) [2] 
    print #this is where newline should come from 

所以我想获得:

 
value1 value2 value3 value4 
value5 value6 value7 value8 
... 

基本上这个方法可以使可读性我的计划(每个真实行有超过20个计算位置)。相反的方式是将所有数据连接成一个长串,但可读性可能会丢失。
是否可以像[1]和[2]中那样使用“print()%()”语法来删除换行符?

+1

请问你刚找到一份工作的方法,如果你使用[str.format(http://docs.python.org/library/stdtypes.html#str.format)而不是旧式%格式?我知道至少会有逗号,尽管我怀疑这会使用%格式。 (尽管如此,你仍然应该使用str.format) – Josiah 2012-08-07 09:46:16

回答

6

如果在声明的末尾添加一个逗号(,),换行符将被省略:

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

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

一个'\n'字符在年底写的,除非print声明以逗号结尾。如果声明仅包含关键字print,这是唯一的行动。

+0

要添加','不能在Python3中工作。 http://stackoverflow.com/questions/493386/how-to-print-in-python-without-newline-or-space# – Stallman 2015-09-20 12:34:10

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

+0

我新的关于逗号,但试图添加它)和%,谢谢:-) – przemol 2012-08-07 09:54:10

+0

您也可以使用'sys.stdout.write'来代替打印。在这种情况下,你只会写出你写的那些字符 – 2012-08-07 10:38:25

0

的唯一方式结束做到这一点,而无需使用print小号后面的逗号(或与PY 3/from __future__ import print_function,该end关键字参数),那么你必须立即执行所有打印 - 例如:

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

如果这使可读性成为问题,请考虑将计算逻辑置于f unctions这样就可以做到:

while ...: 
    value1 = calculate_value1() 
    value2 = calculate_value2() 
    value3 = calculate_value3() 
    value4 = calculate_value4() 
    print '%10d %10s %7s %15d' % (value1, value2, value3, value4)