using the * (splat) operator with print

前端 未结 1 2008
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 20:57

I often use Python\'s print statement to display data. Yes, I know about the \'%s %d\' % (\'abc\', 123) method, and the \'{} {}\'.format(\'ab

相关标签:
1条回答
  • 2020-12-20 21:23

    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
    >>>
    
    0 讨论(0)
提交回复
热议问题