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.

Tuesday, October 18, 2011

Differences in print between Python 2.x and Python 3.x

Recently, I started learning Python and installed the latest version available online - Python 3.2. I did this in spite of the fact that the book I was using Practical Programming: An Introduction to Computer Science using Python.

After completing a few exercises using the Python command line, I decided to save my script and execute them from command line. That is when things started to fail. Python would not allow me to print the output. It kept showing the variable to be printed and said SyntaxError: invalid syntax. To illustrate in command line, it was something like:

>>> i=5
>>> print i
File "", line 1
print i
SyntaxError: invalid syntax

Google could not help me with this. Finally, I went with intuition and solved it. I needed to enclose the arguments to print using parenthesis. But the book did not mention it.

This is because the enclosing parenthesis was not a requirement in Python 2.x, but is required in Python 3.x.

It kind of pissed me off (and I am sure I am not the first Python newbie to feel this way), that the language designers did not give a reasonably clear error message for this one.

Karthick S.