温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python3与2版本中print的区别有哪些

发布时间:2020-07-15 11:05:10 来源:亿速云 阅读:313 作者:清晨 栏目:编程语言

这篇文章主要介绍python3与2版本中print的区别有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

区别:Python2中的print是一个关键字,而Python3里的print是一个函数。关键字用法“print 要打印的内容”;函数用法“print(要打印的内容)”。

python3与2版本中print的区别有哪些

总地来说, Python2.7的print不是一个function,而Python3里的print是一个function。
两都调用方式的主要区别如下:

print 'this is a string' #python2.7
print('this is a string') #python3

当然,python2.7里你也可以用括号把变量括起来, 一点都不会错:

print('this is a string') #python2.7

但是python3将print改成function不是白给的:

1. 在python3里,能使用help(print)查看它的文档了, 而python2不行:

>>help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

2 . 在python3里,能更方便的使用输出重定向
python2.7里,你需要以类似于C++的风格完成重定向:

with open('print.txt', 'w') as f:
    print >> f, 'hello, python!'

在python3里:

with open('print.txt', 'w') as f:
    print('hello, python!', file = f)

file是python3 print新加的一个参数。 另一个很handy的参数是sep, 例如打印一个整数数组, 但你想用星号而不是空格连接。python2时可能需要写一个循环来完成, python3里这样就行了:

a = [1, 2, 3, 4, 5]
print(*a, sep = '*')

最后, 如果想在python2.7里使用python3的print,只需要在第一句代码前加入:

from __future__ import print_function

注意, from __future__ import ...一类的语句一定要放在代码开始处。

以上是python3与2版本中print的区别有哪些的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI