我经常使用Python的print语句来显示数据.是的,我知道'%s %d' % ('abc', 123)方法,'{} {}'.format('abc', 123)方法和' '.join(('abc', str(123)))方法.我也知道splat operator(*)可以用来将iterable扩展为函数参数.但是,我似乎无法用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
Run Code Online (Sandbox Code Playgroud)
使用元组:
>>> 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
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?这根本不可能吗?接下来会发生什么print?该文件说,一个逗号分隔的表达式列表按照print关键字,但我猜这是不一样的列表数据类型.我在SO和网络上做了很多挖掘,并没有找到明确的解释.
我使用的是Python 2.7.6.
iCo*_*dez 12
print是Python 2.x中的一个语句,不支持*语法.您可以从文档中print列出的语法中看到这一点:
print_stmt ::= "print" ([expression ("," expression)* [","]]
| ">>" expression [("," expression)+ [","]])
请注意*在print关键字后面没有使用选项.
然而,*语法是支持内部函数调用,它只是恰巧print是在Python 3.X的功能.这意味着您可以从__future__以下位置导入:
from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)
然后使用:
print(*l)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> # Python 2.x interpreter
>>> from __future__ import print_function
>>> l = [1, 2, 3]
>>> print(*l)
1 2 3
>>>
Run Code Online (Sandbox Code Playgroud)