3

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] ?

pb100
  • 736
  • 3
  • 11
  • 20
  • 1
    Would the methods you've found work if you used [str.format](http://docs.python.org/library/stdtypes.html#str.format) instead of old style % formatting? I know at least the comma will, though I suspect that will work with % formatting. (You should still be using str.format though) – Josiah Aug 07 '12 at 09:46

3 Answers3

6

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 print statement ends with a comma. This is the only action if the statement contains just the keyword print.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • To add `,` can't work in Python3. http://stackoverflow.com/questions/493386/how-to-print-in-python-without-newline-or-space# – Alston Sep 20 '15 at 12:34
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

Note , at the end of prints

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
0

The only way to do this without using prints 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)
lvc
  • 34,233
  • 10
  • 73
  • 98