V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
oldbird
V2EX  ›  Python

py2 中,两种 print( )是什么区别?

  •  
  •   oldbird · 2019-04-16 09:14:02 +08:00 · 3201 次点击
    这是一个创建于 1831 天前的主题,其中的信息可能已经有所发展或是发生改变。

    加与不加 from future import print_function 这一句,都可以用 print()函数。 加了这一句,print()的语法是 print(*objects, sep=' ', end='\n', file=sys.stdout) 不加的话,和普通的 print 语句一样?

    7 条回复    2019-04-16 19:19:24 +08:00
    lithiumii
        1
    lithiumii  
       2019-04-16 09:30:52 +08:00
    py2 的 print 是保留的关键字,用法是 print 空格 object,from future import print_function 之后应该就是 py3 的 print
    但是都 2019 年了,py2 还有八个半月就要光荣退休了,研究这个干啥……
    https://pythonclock.org/
    goodleixiao
        2
    goodleixiao  
       2019-04-16 09:32:08 +08:00
    py2 print 是一个标准的语法关键字,py3 编程一个普通的函数, 导入支持添加了一个 print 函数,跟 py3 补齐功能。
    cosven
        3
    cosven  
       2019-04-16 10:34:10 +08:00
    首先,在 Python 2 中,它们(的效果)是不一样的。请看下面这个例子:

    >>> print 'hello world', 'miao'
    hello world miao
    >>> print('hello world', 'miao')
    ('hello world', 'miao')
    >>> from __future__ import print_function
    >>> print('hello world', 'miao')
    hello world miao

    这个例子说明一个问题:虽然在 Python 2 中,我们也能用 print + 括号的语法,但是它的意义是不一样的。

    在 Python 2 中,你不能把 print 叫做“函数”,它是一个保留的关键字,`print xxx` 是个语句( statement )。

    在 Python 3 中,print 是个函数,不再是关键字,`print(xxx)` 是个表达式( expression )。

    ps:表达式和语句最大的区别就是表达式有返回值,而语句不会有,举个例子,在 Python 3 中,`print(xxx)` 的返回值是 None。
    Outliver0
        4
    Outliver0  
       2019-04-16 10:36:26 +08:00
    python2.7 兼容一些 python3 的特性,是一个过度版本
    xpresslink
        5
    xpresslink  
       2019-04-16 12:01:17 +08:00
    因为在解释器中括号是个定界符。
    所以在 py2 中, 你写成 print ... => print (...) => print(...) 都是等效的。
    并不是你写成 print(...)就是函数了。
    siteshen
        6
    siteshen  
       2019-04-16 13:00:48 +08:00
    补充一下 @cosven 说的内容。
    如果你看到 python2 `print('hello, world')` 打印的内容和 `print 'hello, world'` 一样,不要觉得奇怪,因为
    `('hello, world')` 这个表达式的返回值是 `'hello, world'`。
    所以 `print('hello, world')` 等价于 `print 'hello, world'`

    而 `print('hello', 'world')` 和 `print 'hello', 'world'` 不一样,是因为:
    `('hello', 'world')` 这个表达式的返回值是 `('hello', 'world')` (tuple)。
    Qzier
        7
    Qzier  
       2019-04-16 19:19:24 +08:00
    淘汰的东西不值得研究。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2916 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 03:50 · PVG 11:50 · LAX 20:50 · JFK 23:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.