-2

I am very new to Python.I was using this formatting but I get syntax error every time i try this :

formatter="%r%r%r%r"

print formatter % (1,2,3,4)

SyntaxError: invalid syntax

This is from an example given in the link http://learnpythonthehardway.org/book/

formatter = "%r%r%r%r

print formatter % (1, 2, 3, 4)

I read that there have been some changes in Python 3.0 related to printing statements. Is this because of that?

I am using Python 3.4.0 on a Win-7 system

demouser123
  • 4,108
  • 9
  • 50
  • 82
  • See [here](https://docs.python.org/2/library/string.html#formatstrings) for how you should really be doing string formatting, but @HeavyLight's answer is why your print fails. – aruisdante Apr 29 '14 at 03:46

2 Answers2

4

Yes. print is now a normal function, and must be called with parentheses:

print(formatter % (1,2,3,4))
John Colanduoni
  • 1,596
  • 14
  • 18
1

Look here for more information on what's new in python 3, relating to the print function. Functions are characterized by having open and close parentheses:

E.g.

str.split()
list.reverse()
list.insert(0, 'hi')

In python 2, the following syntax would be fine:

$ python2
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> num = 78
>>> print 'The number is %d' %(num)
The number is 78
>>> 

However, in python 3, because print is a function, you need open and close parentheses:

$ python3
Python 3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan  5 2014, 11:02:52) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> num = 78
>>> print 'The number is %d' %(num)
  File "<stdin>", line 1
    print 'The number is %d' %(num)
                           ^
SyntaxError: invalid syntax
>>> print('The number is %d' %(num))
The number is 78
>>> 

What you need to do is:

formatter="%r%r%r%r"

print(formatter % (1,2,3,4))
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76