Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's ending comma in print function for?

Tags:

python

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.

like image 848
allenhwkim Avatar asked Sep 20 '13 04:09

allenhwkim


People also ask

What does the comma in the print statement do?

When you separate the values by commas, the print function automatically inserts a space between the values. A literal string is a group of characters that is enclosed in quotes. When you print out a literal string, the output is literally everything that is in between the quotes.

What is the use of end in print?

The end parameter in the print function is used to add any string. At the end of the output of the print statement in python. By default, the print function ends with a newline. Passing the whitespace to the end parameter (end=' ') indicates that the end character has to be identified by whitespace and not a newline.

What does end do in a call to the print () function?

end : It is a string appended after the last value, defaults to a newline. It allows the programmer to define a custom ending character for each print call other than the default newline or \n .

What is the purpose of the print () function?

The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.


2 Answers

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.

like image 141
Serial Avatar answered Oct 20 '22 19:10

Serial


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.

like image 29
Mark Ransom Avatar answered Oct 20 '22 18:10

Mark Ransom