1

Right now, I'm working on "How to Think Like A Computer Scientist". I'm on Simple Tables. This lesson is making simple tables. The first example runs fine inside the browser, but when I take it Sublime, the \t symbol prints. It does not do this in the browser. I even copied the code right into sublime.

Here's my code:

print("n", '\t', "2**n")
print("---", '\t', "-----")

for x in range(13):
    print(x, '\t', 2 ** x)

and my result is:

('n', '\t', '2**n')
('---', '\t', '-----')
(0, '\t', 1)
(1, '\t', 2)
(2, '\t', 4)
(3, '\t', 8)
(4, '\t', 16)
(5, '\t', 32)
(6, '\t', 64)
(7, '\t', 128)
(8, '\t', 256)
(9, '\t', 512)
(10, '\t', 1024)
(11, '\t', 2048)
(12, '\t', 4096)

How do I get the parenthesis and the \t symbol to go away. I know that the parenthesis shouldn't be there, so I'm confused with that and I have no idea how to get rid of the \t symbol without getting the "unexpected character" error.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137

1 Answers1

2

I think you're using Python 2 and printing tuples. At the top of your file put from __future__ import print_function and it will look the way you expect. Better yet, upgrade to Python 3! There are installers available for Mac* and PC from the Python website, and most (maybe all?) Linux distributions have Python 3 in the default package manager's repositories.

To explain in a little more detail what's going on, check out one of the Python core developer's answers to another question.

Since you're running Python 2, where print is a statement, the statement only sees one argument: the tuple (x, '\t', 2 ** x). print tries to call __str__ on all the objects it has been given, but since it sees only one object in this case, the tuple, it only tries to call __str__ on that. Since tuple does not define __str__, __repr__ gets called instead. You can see in the source that tuples call repr() on all the items in a tuple. The repr of the string '\t' is '\t'. (This gets into the difference between repr and str in Python a bit). Whenever you use from __future__ import print_function, the function will see three separate arguments, and try to call __str__ on each of them. This will print out the way that you want.

For this specific case, you'll want to make sure spaces do not get inserted between arguments, so put in the keyword argument sep='':

print(x, '\t', 2**, sep='' )

*Note: On Mac OS X it's usually recommended to use Homebrew: http://docs.python-guide.org/en/latest/starting/install3/osx/

Cody Piersall
  • 8,312
  • 2
  • 43
  • 57