python 2.6带格式的打印(百分比):删除newlin

2024-06-26 14:51:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python2.6,阅读了很多关于从“print”中删除新行的链接,但找不到使用模号(%)格式化的示例。在我的程序中,我试图在计算数据的循环行中写入数据,但每行数据都来自不同的计算:

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()%()”语法删除换行符?


Tags: and数据方法程序示例链接print可读性
3条回答
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结尾处

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

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

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

A '\n' character is written at the end, unless the print statement ends with a comma. This is the only action if the statement contains just the keyword print.

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

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)

相关问题 更多 >