将 * (splat) 运算符与 print 一起使用 [英] using the * (splat) operator with print
问题描述
我经常使用 Python 的 print
语句来显示数据.是的,我知道 '%s %d' % ('abc', 123)
方法和 '{} {}'.format('abc', 123)
方法,以及 ' '.join(('abc', str(123)))
方法.我还知道 splat 运算符 (*
) 可用于将可迭代对象扩展为函数参数.但是,我似乎无法使用 print
语句来做到这一点.使用列表:
使用元组:
<预><代码>>>>t = (4, 5, 6)>>>吨(4, 5, 6)>>>打印 t(4, 5, 6)>>>%d %d %d"%t'4 5 6'>>>'{} {} {}'.format(*t)'4 5 6'>>>打印 *t文件<stdin>",第 1 行打印 *t^语法错误:无效语法我错过了什么吗?这根本不可能吗?print
后面到底是什么东西?文档 说用逗号分隔的表达式列表遵循 print
关键字,但我猜这与列表数据类型不同.我在 SO 和网络上做了很多挖掘,但没有找到明确的解释.
我使用的是 Python 2.7.6.
print
是 Python 2.x 中的语句,不支持 *
语法.您可以从 print 语法中看到这一点"noreferrer">文档:
请注意在 print
关键字之后没有使用 *
的选项.
但是,*
语法在函数调用内部被支持,而print
是 Python 3.x 中的一个函数.这意味着您可以从 __future__
导入它:
from __future__ import print_function
然后使用:
print(*l)
演示:
<预><代码>>>># Python 2.x 解释器>>>从 __future__ 导入 print_function>>>l = [1, 2, 3]>>>打印(*l)1 2 3>>>I often use Python's print
statement to display data. Yes, I know about the '%s %d' % ('abc', 123)
method, and the '{} {}'.format('abc', 123)
method, and the ' '.join(('abc', str(123)))
method. I also know that the splat operator (*
) can be used to expand an iterable into function arguments. However, I can't seem to do that with the print
statement. Using a list:
>>> 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
Using a tuple:
>>> 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
Am I missing something? Is this simply not possible? What exactly are the things that follow print
? The documentation says that a comma-separated list of expressions follow the print
keyword, but I am guessing this is not the same as a list data type. I did a lot of digging in SO and on the web and did not find a clear explanation for this.
I am using Python 2.7.6.
print
is a statement in Python 2.x and does not support the *
syntax. You can see this from the grammar for print
listed in the documentation:
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
and then use:
print(*l)
Demo:
>>> # Python 2.x interpreter
>>> from __future__ import print_function
>>> l = [1, 2, 3]
>>> print(*l)
1 2 3
>>>
这篇关于将 * (splat) 运算符与 print 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!