Python中的打印有哪些不同之处:
print 'smth'
print('smth')
print
在 Python 3 中被改为函数形式(而以前是语句),因此你的第一行代码是 Python 2 风格的,后者是 Python 3 风格。
更具体地说,在 Python 2 中,使用 ()
打印意味着打印一个元组:
In [1414]: print 'hello', 'kitty'
hello kitty
In [1415]: print ('hello', 'kitty')
('hello', 'kitty')
In [1416]: print ('hello') #equals: print 'hello',
#since "()" doesn't make a tuple, the commas "," do
hello
()
的print语句会导致SyntaxError错误。In [1]: print ('hello', 'kitty')
hello kitty
In [2]: print 'hello', 'kitty'
File "<ipython-input-2-d771e9da61eb>", line 1
print 'hello', 'kitty'
^
SyntaxError: invalid syntax
print('smth')
是有效的。因为('smth')
等同于写成'smth'
。 - Loïc Faure-Lacroix('smth')
仍然是字符串,但 ('smth',)
是元组。 - J0HN()
不是生成元组的关键,逗号才是。但是 print
语句的语法使逗号有不同的作用,而 ()
又会让它们重新生成元组。 - Wooble((3 + 4) + 4)
,作为 tuple(tuple(3 + 4) + 4)
,除非你能提出一种新的括号类型,而这种类型还没有被使用过。 - Loïc Faure-Lacroix>>> print('a','b','c')
a b c
>>> print 'a','b','c'
a b c
print()
可以使用,但它并不是你想象中的那样。如果有多个元素,它会打印出一个元组:>>> print('a','b','c')
('a', 'b', 'c')
>>> print((((('hello')))))
hello
但这只是Python表达式解析器的操作,而不是print函数的操作:
>>> ((((('hello')))))
'hello'
>>> print((((('hello',)))))
('hello',)
您可以通过导入来在Python 2中获得Python 3的打印函数:
>>> print('a','b','c')
('a', 'b', 'c')
>>> from __future__ import print_function
>>> print('a','b','c')
a b c
PEP 3105讨论了这个变化。
在Python 2和3的print
中您可以使用括号,但在Python 3中必须使用它们。
Python 2:
print "Hello"
或者:
print("Hello")
而在Python 3中:
print "Hello"
让你得到这个:
File "<stdin>", line 1
print "Hello"
^
SyntaxError: Missing parentheses in call to 'print'
所以你需要做:
print("Hello")
print
是一个语句,但在Python 3中,它是一个函数。
print
是语句而不是函数的情况下才能巧合地起作用。而第一种方法才是正确的用法,它不是语法糖。 - Wooble