Saturday, October 22, 2011

Special options while printing in Python 3.x

One more post about printing values in Python 3.x and how it differs with Python 2.x.

To print the end of line using Python 2.x, all you need to do is add a comma to the end of the print list.

print "Hello ",
print "World"

The statements above print "Hello World" on the screen.

But with Python 3.x, it is different

print ("Hello ", end='')
print ("World")

This prints "Hello World" on the screen.

Another way to print the same would be:

print ("Hello", end=" ")
print ("World")

In other words, whatever is sent as a value for end is appended to the end of whatever is printed. You can even specify multi-character strings as the value for end.

In addition to this, there is another argument sep, which specifies the separator between the items to be printed.

print ("Hello", "World", sep = " ")

This would help in creating output as a CSV or a TSV files for example:

print ("FirstName", "LastName", sep=",")

Karthick S.

Post a Comment