[Tutor] Python printing parentheses and quotes

Cameron Simpson cs at cskk.id.au
Mon Jun 10 20:34:34 EDT 2019


On 10Jun2019 19:04, Sai Allu <sai.allu at nutanix.com> wrote:
>Actually I'm pretty sure what happened was that the "#! usr/bin/python" was in a module that was being imported. So the Python interpreter cached it or somehow crashed randomly, which meant that the print was working as a keyword instead of a function.
>
>But when I removed that "#! usr/bin/python" line and then rewrote the print statements, it went back to working normally.

My personal suspicision is that what you might have been doing is this 
(notice the trailing comma):

  print("",)

or maybe:

  print("this", that")

Look:

  % python
  Python 2.7.16 (default, Apr  1 2019, 15:01:04)
  [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
  Type "help", "copyright", "credits" or "license" for more information.
  >>> print("",)
  ('',)
  >>>

  % python3
  Python 3.7.3 (default, Mar 30 2019, 03:38:02)
  [Clang 8.0.0 (clang-800.0.42.1)] on darwin
  Type "help", "copyright", "credits" or "license" for more information.
  >>> print("",)

  >>>

What is happening?

In Python 2, print is a statement unless you use the __future__ import 
already mentioned. That means that this:

  print("",)

is a "print" of the expression ("",), which is a 1-tuple, and gets 
printed as a tuple. The more likely scenario is when you're printing 
mulitple things:

  print("this", "that")

which is still a "print" of a tuple.

However, in Python 3 print is a function which means that the brackets 
are part of the function call. So this:

  print("")

or:

  print("this", "that")

is a call to the "print()" function, passing one or two arguments, which 
get printed. And printing "" (the former case) is an empty string.

Please revisit your code can test this.

Subtle issues like this are why we like to receive _exact_ cut/paste of 
your code and the matching output, not a retype of what you thought you 
ran. If you encounter something weird like this, it is well worth your 
time (and ours) if you make a tiny standalone script showing the 
problem, as small as possible. Then paste it into your message and paste 
in the output (this list drops attachments). That we we can all run 
exactly the same code, and solve your actual problem.

And start always using:

  from __future__ import print_function

in Python if you're using print. That will make your prints behave the 
same regardless if whether they are using Python 2 or 3.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list