今天遇到了一些有趣的 Python 行为。我以为我在写
print("{}".format("some value"))
但是我写了
print("{}").format("some value")
有趣的是,它起作用了。所以我的问题是,这是如何运作的?
深入挖掘
这种行为似乎是 python2 特有的。
Python2.7
>>> print("{}").format("testing")
testing
Python3.4
>>> print("{}").format("testing)
File "<stdin>", line 1
print("{}").format("testing)
^
SyntaxError: EOL while scanning string literal
貌似python2的print函数没有返回值,而Python3有?这让我更加困惑。
Python2.7
>>> type(print("testing))
File "<stdin>", line 1
type(print("testing))
^
SyntaxError: invalid syntax
>>> a = print("testing")
File "<stdin>", line 1
a = print("testing")
^
SyntaxError: invalid syntax
Python3.4
>>> type(print("{}"))
{}
<class 'NoneType'>
>>> a = print("{}")
{}
>>> a
>>> type(a)
<class 'NoneType'>
请您参考如下方法:
在 Python 2 中,print 是一个语句,而不是一个函数(除非您在模块顶部执行 from __future__ import print_function)。这意味着您正在打印的内容周围的括号不是函数调用的一部分,而只是被视为分组括号。在您描述的情况下 ("{}") 与 "{}" 相同(parens 什么都不做),因此 format如果您编写 "{}".format(...).
在 Python 3 中,print 是一个函数,所以括号不是可选的,不能放错地方。 print 返回 None,因此如果您执行 print(something).something_else,几乎肯定会出错,因为 None 没有 something_else 属性。
