python中的默認編碼使用
python默認編碼
python2中,默認使用的是ASCII編碼。
這個編碼和開頭的encoding不同之處在于,開頭的encoding是對于文件內容的編碼,默認編碼是一些python方法中默認使用的編碼。
比如對str進行encode的時候默認先decode的編碼,比如文件寫操作write的encode的編碼等。
python3中默認使用的是UTF-8編碼
sys.getdefaultencoding() 獲取默認編碼
import sys print(sys.getdefaultencoding())
- python2
D:\SoftInstall\Python\Python38\python3.exe E:/PycharmProjects/displayPY3/1.py
asciiProcess finished with exit code 0
- python3
D:\SoftInstall\Python\Python38\python3.exe E:/PycharmProjects/displayPY3/1.py
utf-8Process finished with exit code 0
sys.setdefaultencoding(編碼格式) 修改默認編碼
下面這個例子,用python2環(huán)境
# coding=utf-8
import sys
print(sys.getdefaultencoding())
reload(sys)
sys.setdefaultencoding('utf-8')
print(sys.getdefaultencoding())
s = '中文'
s.encode('utf-8')
print(s)
#等價于s.decode(“utf-8”).encode('utf8')E:\PycharmProjects\LEDdisplay2\venv\Scripts\python.exe E:/PycharmProjects/LEDdisplay2/2.py
ascii
utf-8
中文
如果上述代碼沒有修改默認編碼,就會使用默認編碼ASCII來decode變量s,就會報錯
# coding=utf-8
import sys
print(sys.getdefaultencoding())
s = '中文'
s.encode('utf-8')
print(s)E:\PycharmProjects\LEDdisplay2\venv\Scripts\python.exe E:/PycharmProjects/LEDdisplay2/2.py
ascii
Traceback (most recent call last):
File "E:/PycharmProjects/LEDdisplay2/2.py", line 5, in <module>
s.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)Process finished with exit code 1
上述代碼為什么需要reload(sys)?
請看下面的代碼:
# coding=utf-8
import sys
print(sys.getdefaultencoding())
# reload(sys)
sys.setdefaultencoding('utf-8')
print(sys.getdefaultencoding())
s = '中文'
s.encode('utf-8')
print(s)E:\PycharmProjects\LEDdisplay2\venv\Scripts\python.exe E:/PycharmProjects/LEDdisplay2/2.py
Traceback (most recent call last):
File "E:/PycharmProjects/LEDdisplay2/2.py", line 5, in <module>
sys.setdefaultencoding('utf-8')
AttributeError: 'module' object has no attribute 'setdefaultencoding'
asciiProcess finished with exit code 1
reload是用于重新加載之前import的模塊。
這里需要重新加載sys的原因是:
python在加載模塊時候刪除了sys中的setdefaultencoding方法(可能是出于安全起見),所以需要reload這個sys模塊。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python中使用__new__實現(xiàn)單例模式并解析
單例模式是一個經(jīng)典設計模式,簡要的說,一個類的單例模式就是它只能被實例化一次,實例變量在第一次實例化時就已經(jīng)固定。 這篇文章主要介紹了Python中使用__new__實現(xiàn)單例模式并解析 ,需要的朋友可以參考下2019-06-06
Python使用Python-docx庫實現(xiàn)Word文檔自動化
在日常辦公中,Word文檔處理是高頻需求,無論是生成報告、合同,還是批量修改文檔內容,手動操作效率低下且易出錯,Python-docx作為Python生態(tài)中處理.docx文件的王牌庫,本文將帶您全面掌握該庫的核心功能,并附實戰(zhàn)代碼示例,需要的朋友可以參考下2025-12-12
Python文件監(jiān)聽工具pyinotify與watchdog實例
今天小編就為大家分享一篇關于Python文件監(jiān)聽工具pyinotify與watchdog實例,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10
Python實現(xiàn)的單向循環(huán)鏈表功能示例
這篇文章主要介紹了Python實現(xiàn)的單向循環(huán)鏈表功能,簡單描述了單向循環(huán)鏈表的概念、原理并結合實例形式分析了Python定義與使用單向循環(huán)鏈表的相關操作技巧,需要的朋友可以參考下2017-11-11

