python中的默認(rèn)編碼使用
python默認(rèn)編碼
python2中,默認(rèn)使用的是ASCII編碼。
這個編碼和開頭的encoding不同之處在于,開頭的encoding是對于文件內(nèi)容的編碼,默認(rèn)編碼是一些python方法中默認(rèn)使用的編碼。
比如對str進行encode的時候默認(rèn)先decode的編碼,比如文件寫操作write的encode的編碼等。
python3中默認(rèn)使用的是UTF-8編碼
sys.getdefaultencoding() 獲取默認(rèn)編碼
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(編碼格式) 修改默認(rèn)編碼
下面這個例子,用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
中文
如果上述代碼沒有修改默認(rèn)編碼,就會使用默認(rèn)編碼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模塊。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Python實現(xiàn)圖像標(biāo)記點的坐標(biāo)輸出功能
這篇文章主要介紹了使用Python實現(xiàn)圖像標(biāo)記點的坐標(biāo)輸出功能,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2019-08-08
淺談keras中l(wèi)oss與val_loss的關(guān)系
這篇文章主要介紹了淺談keras中l(wèi)oss與val_loss的關(guān)系,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python?subprocess執(zhí)行外部命令常用方法詳細(xì)舉例
這篇文章主要給大家介紹了關(guān)于python?subprocess執(zhí)行外部命令常用方法的相關(guān)資料,Python的subprocess模塊提供了一種在Python中調(diào)用外部命令的方法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
django模型層(model)進行建表、查詢與刪除的基礎(chǔ)教程
這篇文章主要給大家介紹了關(guān)于django模型層(model)進行建表、查詢與刪除的等基礎(chǔ)操作的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11

