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
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 :
from __future__ import print_function print(*l, sep='')
or directly call the function by accessing it via the __builtin__
module :
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.