What’s ending comma in print function for?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

Method 3

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.

Method 4

in python 2.7:

print line,

in python 3.x:

print(line, end = ' ')


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x