码迷,mamicode.com
首页 > 编程语言 > 详细

python3与python2不一样的地方

时间:2019-05-24 00:48:31      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:byte   路径   rom   函数   交互   中文字符   xxxx   txt   问题   

进入不同语言版本的Python交互环境
py -2
py -3

pip 命令的执行 :
py -2 -m pip install xxxx
py -3 -m pip install nose

执行python文件
py -2 a.py
py -3 a.py

py2:
print "hello"

py3:
print("hello")


如果不想py -2这样进入python2,可以
进入到python27的安装目录
把python.exe 修改为python2.exe
在环境变量里面加入这个Python27的路径

python3 a.py
pip3 install


python3:str类型---》相当于py2的unicode类型
str类型encode之后变为了bytes类型---》相当于python2的str类型

print(s.encode("gbk"))
b‘\xce\xd2\xc3\xc7‘

print(s.encode("gbk").decode("gbk"))
我们


文件操作

在python3中,默认编码环境为utf8,故不需要像py2那样在文件头指定编码,但是在open()函数多一个encoding参数,在python2是没有的

with open('d:\\gloryroad\\1.txt','r',encoding='utf8') as fp:
...  print(fp.read())
...
abbcddeeegiiiilmnnooooorrrstuvyz
中文

在python3中,write函数里面必须是str类型的

with open('d:\\gloryroad\\1.txt','w',encoding='utf8') as fp:
...  fp.write("我们\n你们\n".encode('utf8'))
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: write() argument must be str, not bytes

在python3中连接数据库的包是PyMySQL,python2是MySQLdb,连接方法都一样。


序列化

python3没有cpickle,只有pickle


多线程

thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 Python3 中不能再使用"thread" 模块。为了兼容性,Python3 将 thread 重命名为 "_thread"。


队列

python3的queue模块是小写,py2是Queue,因此
import queue

q=queue.Queue(5)
q.put(2)
q.get()
2
q
<queue.Queue object at 0x00000000022AAE80>


使用中文格式化时间
from datetime import datetime
nt=datetime.now()
print(nt.strftime(‘%Y年%m月%d日 %H时%M分%S秒‘)) --->报错
法1:

import locale
locale.setlocale(locale.LC_CTYPE, ‘chinese‘)
print(nt.strftime(‘%Y年%m月%d日‘))
2015年08月10日
原理是:“在Windows里,time.strftime使用C运行时的多字节字符串函数strftime,这个函数必须先根据当前locale配置来编码格式化字符串(使用PyUnicode_EncodeLocale)。”如果不设置好locale的话,根据默认的"C" locale,底层的wcstombs函数会使用latin-1编码(单字节编码)来编码格式化字符串,然后导致题主提供的多字节编码的字符串在编码时出错。
法2:
print(nt.strftime(‘%Y{y}%m{m}%d{d}‘).format(y=‘年‘, m=‘月‘, d=‘日‘))
原理是:既然直接丢中文字符进去会出错,那么就绕过这个问题,丢(可能)永远不会出错的ascii字符进去充当占位符,格式化完毕后再将占位符换回中文字符。
法3:
print(time.strftime(‘%Y年%m月%d日‘))
2019年05月23日

python3与python2不一样的地方

标签:byte   路径   rom   函数   交互   中文字符   xxxx   txt   问题   

原文地址:https://www.cnblogs.com/kknote/p/10915424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!