我对Python很陌生。我使用这种格式,但每次尝试时都会出现语法错误:
formatter="%r%r%r%r"
print formatter % (1,2,3,4)
SyntaxError: invalid syntax
这是链接中给出的一个例子http://learnpythonthehardway.org/book/
formatter = "%r%r%r%r
print formatter % (1, 2, 3, 4)
我读到Python 3.0中有一些与打印语句相关的更改。这是因为那个吗?
我在Win-7系统上使用Python 3.4.0
是。print
现在是一个正常函数,必须用括号调用:
print(formatter % (1,2,3,4))
查看此处以获取有关python 3中与print
函数相关的新功能的更多信息。函数的特点是有开括号和闭括号:
例如
str.split()
list.reverse()
list.insert(0, 'hi')
在python 2中,可以使用以下语法:
$ 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
>>>
然而,在python 3中,因为print
是一个函数,所以需要开括号和闭括号:
$ 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
>>>
你需要做的是:
formatter="%r%r%r%r"
print(formatter % (1,2,3,4))