python2和3的区别

Python 2和Python 3的区别

兼容

为了兼容python 2和python 3,可以使用_future_库。

差异

print函数

python2

可以不写括号,也可以使用括号!

print("hello 2.7")
print "hello 2.7"

unicode

python2中有两种字符串类型:Unicode字符串和非Unicode字符串。Python3中只有一种类型:Unicode字符串。

python 2如果,不用类似pycharm(默认指定为UTF-8)的开发环境打开,默认使用的是ascii编码,进行解释代码,如果字符有中文就会报错。

解决方法:指定以什么编码运行代码,比如指定utf-8,或者使用u,指定unicode编码

# coding:utf-8
print "你好呀"
print u'你好呀'

指定了编码还可能出的错

代码详情 Python2执行情况 Python3执行情况
# coding:gbk print('中') 终端:utf8 乱码 不乱码
# coding:utf8 print('中') 终端:utf8 不乱码 不乱码
# coding:gbk print(u'中') 终端:utf8 不乱码 不乱码
# coding:utf8 print(u'中') 终端:utf8 不乱码 不乱码

其他差别可以参考大佬的博客:https://www.cnblogs.com/meng-wei-zhi/articles/8194849.html

原文地址:https://www.cnblogs.com/zx125/p/11323532.html