我经常使用 Python 的 print
语句来显示数据。是的,我知道 '%s %d' % ('abc', 123)
方法和 '{} {}'.format('abc', 123)
方法和 ' '.join(('abc', str(123)))
方法。我还知道 splat 运算符 (*
) 可用于将可迭代对象扩展为函数参数。但是,我似乎无法使用 print
语句来做到这一点。使用列表:
>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> print l
[1, 2, 3]
>>> '{} {} {}'.format(*l)
'1 2 3'
>>> print *l
File "<stdin>", line 1
print *l
^
SyntaxError: invalid syntax
使用元组:
>>> t = (4, 5, 6)
>>> t
(4, 5, 6)
>>> print t
(4, 5, 6)
>>> '%d %d %d' % t
'4 5 6'
>>> '{} {} {}'.format(*t)
'4 5 6'
>>> print *t
File "<stdin>", line 1
print *t
^
SyntaxError: invalid syntax
我错过了什么吗?这根本不可能吗? print
后面的内容到底是什么? documentation表示逗号分隔的表达式列表跟在 print
关键字之后,但我猜这与列表数据类型不同。我在 SO 和网络上进行了大量挖掘,但没有找到明确的解释。
我正在使用 Python 2.7.6。
最佳答案
print
是 Python 2.x 中的语句,不支持 *
语法。您可以从 documentation 中列出的 print
的语法中看出这一点。 :
print_stmt ::= "print" ([expression ("," expression)* [","]] | ">>" expression [("," expression)+ [","]])
Notice how there is no option for using *
after the print
keyword.
However, the *
syntax is supported inside function calls and it just so happens that print
is a function in Python 3.x. This means that you could import it from __future__
:
from __future__ import print_function
然后使用:
print(*l)
演示:
>>> # Python 2.x interpreter
>>> from __future__ import print_function
>>> l = [1, 2, 3]
>>> print(*l)
1 2 3
>>>
关于python - 在 print 中使用 * (splat) 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29503331/