python小結(三) py-2與py-3的偏碼真相&&幾個呼叫模組的區別
阿新 • • 發佈:2019-02-05
編碼的不同
0x01:
python2.X
1.python2預設的編碼的格式是ASCII,所以通常在前面都會宣告 coding:utf8
2.按照python2的編碼方式會以bytes位元組的方式儲存的你的硬碟中,而且python2會預設將bytes位元組轉化為unicode格式
如圖所示:
python3.X
1.python3預設的編碼格式是utf8
2.python3則將str與bytes的型別做了嚴格的區分,str就是unicode型別,也是最常用的型別,只有在需要bytes時才會轉化為bytes型別
如圖所示:
模組的區別
0x02:
1.input
python2.X
inp = raw_input('請輸入:')
python3.X
input = input('請輸入')
2. json模組:
python2.X
data= {'name':'張三'} data = json.dumps(data,ensure_ascii=False) print data 執行結果: {"name": "張三"} 若沒有新增ensure_ascii屬性,則 {"name": "\u5f20\u4e09"}
python3.X
data= {'name':'張三'} data = json.dumps(data) print(data) 執行結果: data= {'name':'張三'}
3.configparser
python2.X
import ConfigParser config.add_section('default') config.set('default','name','tom') with open('example', 'w') as f: config.write(f)
python3.X
import configparser config = configparser.ConfigParser() config['deault'] = { '':'', '':'' } with open('example', 'w') as f: config.write(f)
4.socket(以server端為例)
python2.X
傳送send(),接受recv(),python2中可以是str或者bytes型別
import socket import SocketServer class MyServer(SocketServer.BaseRequestHandler): def handle(self): print ("服務端啟動...") while True: conn = self.request print (self.client_address) while True: client_data=conn.recv(1024) print (client_data) print ("waiting...") server_response = raw_input(">>>") conn.sendall(server_response) conn.close() if __name__ == '__main__': server = SocketServer.ThreadingTCPServer(('127.0.0.1',8090),MyServer) server.serve_forever()
python3.X
只能接受bytes型別的資料
import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): print ("服務端啟動...") while True: conn = self.request print (self.client_address) while True: client_data=conn.recv(1024) print (str(client_data,"utf8")) print ("waiting...") server_response=input(">>>") conn.sendall(bytes(server_response,"utf8")) conn.close() if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1',8098),MyServer) server.serve_forever()
5.cmd
python2.X
a)cm命令列預設的是gbk格式,當python2在命令列執行漢字會出現亂碼或報錯
print u'張三'
b)也可以修改cmd的預設格式
1. chcp 65001 ( 將字元格式修改為utf8 )
2. chcp 936 ( 將字元格式修改為預設的gbk)
python3.X
python3則沒有這樣的問題
暫時想起來這麼多,有的遇到了,查完也就忘了。如果以後遇到還會補充,也希望大神留言告知其他的方面