Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

python - using the * (splat) operator with print

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
>>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...