I use python 2.6 and have read many links about removing new line from 'print' but cannot find example of usage together with formating using modulo sign (%). In my program I am trying to write in a loop line of calculated data but each line data comes from different calculations:
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
So I would like to get:
value1 value2 value3 value4 value5 value6 value7 value8 ...
Basically this approach keeps readability of my program (each real line has over 20 calculated positions). The opposite way would be to concatenate all data into one, long string but readability could be lost.
Is it possible to remove newline using "print () % ()" syntax as in [1] and [2] ?
If you add a comma ( ,
) at the end of the statement, the newline will be omitted:
print ('%10d %10s') % (value1, value2),
From http://docs.python.org/reference/simple_stmts.html#print :
A
'\\n'
character is written at the end, unless the
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
Note ,
at the end of prints
The only way to do this without using print
s trailing comma (or, with Py3/ from __future__ import print_function
, the end
keyword argument), then you do have to do all your printing at once - ie:
while ...:
# calulating value1 and value2
# calulating value3 and value4
print '%10d %10s %7s %15d' % (value1, value2, value3, value4)
If this makes readability an issue, consider putting the calculation logic into functions so that you can do:
while ...:
value1 = calculate_value1()
value2 = calculate_value2()
value3 = calculate_value3()
value4 = calculate_value4()
print '%10d %10s %7s %15d' % (value1, value2, value3, value4)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.