简体   繁体   English

为Python 2解压缩打印列表

[英]Unpacking a list in print for Python 2

I'm having problem with understanding why unpacking does not work with list and print statement in Python 2.7: 我有理解为什么解包不适用于Python 2.7中的list和print语句的问题:

>>> l=['a', 'b', 'c']
>>> print (*l, sep='')

Python 3.x works fine and prints: Python 3.x工作正常并打印:

abc

Python 2.7, however, raises an error: 但是,Python 2.7引发了一个错误:

 print (*l, sep='')
       ^
SyntaxError: invalid syntax

How can I make it work for Python 2.7? 我怎样才能使它适用于Python 2.7?

I know I can alternatively code it using join with: ''.join(l) 我知道我可以使用join来编写代码: ''.join(l) join ''.join(l)

Because print isn't a function in Python 2; 因为print不是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: 您需要从__future__导入print_function以支持此操作:

>>> from __future__ import print_function

Now unpacking is possible: 现在拆包是可能的:

>>> l = ['a', 'b', 'c']
>>> print(*l, sep='')
abc

You have two options: 您有两种选择:

  • Convert to strings and join with spaces manually: 转换为字符串并手动连接空格:

     print ''.join(map(str, l)) 
  • Use the print() function , by using the from __future__ import that disables the print statement : 使用print() 函数 ,使用from __future__ import禁用print 语句

     from __future__ import print_function print(*l, sep='') 

    or directly call the function by accessing it via the __builtin__ module : 或通过__builtin__模块访问该函数直接调用该函数:

     import __builtin__ print_function = getattr(__builtin__, 'print') print_function(*l, sep='') 

    The same function is available in both Python 2 and 3, but in Python 2 you can't use it directly without first disabling keyword. Python 2和3中都提供了相同的功能,但在Python 2中,如果没有首先禁用关键字,则无法直接使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM