Python 2.7与Python3 的print有什么区别?
2017-05-11 16:58
465 查看
总地来说, Python2.7的print不是一个function,而Python3里的print是一个function。
两都调用方式的主要区别如下:
当然,python2.7里你也可以用括号把变量括起来, 一点都不会错:
但是python3将print改成function不是白给的:
1. 在python3里,能使用
2 . 在python3里,能更方便的使用输出重定向
python2.7里,你需要以类似于C++的风格完成重定向:
在python3里:
最后, 如果想在python2.7里使用python3的print,只需要在第一句代码前加入:
注意,
两都调用方式的主要区别如下:
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 ...一类的语句一定要放在代码开始处。
References
http://www.cnblogs.com/kaitoex/p/6085606.html相关文章推荐
- python2.7里的StringIO.StringIO与BytesIO有什么区别
- Python2.7中input和raw_input函数有什么区别
- leetcode-1:python基础,循环、条件、列表、字典的应用,enumerate、range函数以及2.0和3.0print的区别
- python中的print()语句中的end=''是什么意思
- Python3字典中items()和python2.x中iteritems()有什么区别
- ubuntu 16.04 安装 python2.7 以及 cv2, dist-package 和 site-package 的区别, import cv2 出问题解答
- python 2.7 命令行打印、print、str()、repr()
- Window下python2.7在使用reload(sys)后,再使用print语句无输出的解决方法
- python中print和repr区别一瞥
- python 普通方法、静态方法和类方法有什么区别?
- Python2.7 Print函数
- python print 函数与print语句区别
- python2.7在使用reload(sys)后,再使用print语句无输出,有解决办法吗?
- python2.7系列下的print函数使用注意事项
- Python的静态方法和类方法有什么区别
- python 除法 /与//在2.7*和3.*版本的区别
- Python 3.5 和 2.7区别
- echo() print() print_r()的区别是什么
- python #coding:utf-8和setdefaultencoding有什么区别?
- 【python2.7】raw_input()和input()区别及用法