Unpacking a list for printing in Python 2

I had a problem understanding why unpacking doesn't work with list and print operator 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 that I can alternatively encode it using join: ''.join(l)

+4
source share
2 answers

Because it is printnot a function in Python 2; Unpacking the list and providing it as positional arguments is not possible if it is not a function.

You need to import print_functionfrom __future__to support this:

>>> from __future__ import print_function

:

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

:

  • :

    print ''.join(map(str, l))
    
  • print() , from __future__, print:

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

    , __builtin__ module:

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

    Python 2, 3, Python 2 , .

+3

Source: https://habr.com/ru/post/1663269/


All Articles