为 Python 2 解压打印列表 [英] Unpacking a list in print for Python 2
问题描述
我无法理解为什么在 Python 2.7 中解包不适用于 list 和 print 语句:
<预><代码>>>>l=['a', 'b', 'c']>>>打印 (*l, sep='')Python 3.x 工作正常并打印:
abc
然而,Python 2.7 引发了一个错误:
打印 (*l, sep='')^语法错误:无效语法
如何使其适用于 Python 2.7?
我知道我也可以使用 join 对其进行编码:''.join(l)
因为 print
不是 Python 2 中的函数;解包一个列表并将其作为位置参数提供如果它不是一个函数是不可能的.
您需要从 __future__
导入 print_function
以支持此功能:
现在可以解包了:
<预><代码>>>>l = ['a', 'b', 'c']>>>打印(*l, sep='')美国广播公司I'm having problem with understanding why unpacking does not work with list and print statement in Python 2.7:
>>> l=['a', 'b', 'c']
>>> print (*l, sep='')
Python 3.x works fine and prints:
abc
Python 2.7, however, raises an error:
print (*l, sep='')
^
SyntaxError: invalid syntax
How can I make it work for Python 2.7?
I know I can alternatively code it using join with: ''.join(l)
Because print
isn't a function in Python 2; unpacking a list and providing it as positional args isn't possible if it isn't a function.
You'll need to import the print_function
from __future__
in order to support this:
>>> from __future__ import print_function
Now unpacking is possible:
>>> l = ['a', 'b', 'c']
>>> print(*l, sep='')
abc
这篇关于为 Python 2 解压打印列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!