45

This code is from http://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions

with open("myfile.txt") as f:
    for line in f:
        print line,

What I don't understand is what's that , for at the end of print command.

I also checked doc, http://docs.python.org/2/library/functions.html#print.

Not understanding enough, is it a mistake?(it seems not. it's from the official tutorial).

I am from ruby/javascript and it's unusual for me.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
allenhwkim
  • 27,270
  • 18
  • 89
  • 122

4 Answers4

60

In python 2.7, the comma is to show that the string will be printed on the same line

For example:

for i in xrange(10):
     print i,

This will print

1 2 3 4 5 6 7 8 9 

To do this in python 3 you would do this:

 for i in xrange(10):
      print(i,end=" ")

You will probably find this answer helpful

Printing horizontally in python

---- Edit ---

The documentation, http://docs.python.org/2/reference/simple_stmts.html#the-print-statement, says

A '\n' character is written at the end, unless the print statement ends with a comma.

Community
  • 1
  • 1
Serial
  • 7,925
  • 13
  • 52
  • 71
15

It prevents the print from ending with a newline, allowing you to append a new print to the end of the line.

Python 3 changes this completely and the trailing comma is no longer accepted. You use the end parameter to change the line ending, setting it to a blank string to get the same effect.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 3
    That seems a wise a movement – allenhwkim Sep 20 '13 at 04:42
  • 7
    More like a necessary consequence. When ``print`` is a normal function and not a statement, you can't just add random syntax to it. – fjarri Sep 20 '13 at 04:50
  • 1
    This makes much more sense in Python3. The original syntax was really a weird exception out of nowhere that easily confuses people. – xji Mar 15 '17 at 18:03
  • 2
    @JIXiang I think it was a feature copied from older languages, I vaguely remember seeing a BASIC that worked that way. I agree the Python 3 way is much better. – Mark Ransom Mar 15 '17 at 18:24
5

From Python trailing comma after print executes next instruction:

  1. In Python 2.x, a trailing , in a print statement prevents a new line to be emitted.
  2. The standard output is line-buffered. So the "Hi" won't be printed before a new line is emitted.
Community
  • 1
  • 1
shanet
  • 7,246
  • 3
  • 34
  • 46
0

in python 2.7:

print line,

in python 3.x:

print(line, end = ' ')
jeremysprofile
  • 10,028
  • 4
  • 33
  • 53
  • 1
    Hello, and welcome to the site! Could you please elaborate on this answer? This shows how to get the same result in Python 2 and Python 3, but it doesn't explain what that result is. – MackM Oct 09 '18 at 18:43