‘ascii‘ codec can‘t encode characters in position
??????UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-15: ordinal not in range(128)
python在安裝時(shí),默認(rèn)的編碼是ascii,當(dāng)程序中出現(xiàn)非ascii編碼時(shí),python的處理常常會(huì)報(bào)類似這樣的錯(cuò)誤。
UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-15: ordinal not in range(128)python沒辦法處理非ascii編碼的,此時(shí)需要自己設(shè)置將python的默認(rèn)編碼,一般設(shè)置為utf8的編碼格式。
? ? 查詢系統(tǒng)默認(rèn)編碼:
import sys;sys.getdefaultencoding()設(shè)置默認(rèn)編碼
import sys;sys.setdefaultencoding('utf8')? ? 可能會(huì)報(bào)AttributeError: 'module' object has no attribute 'setdefaultencoding'的錯(cuò)誤,執(zhí)行reload(sys),在執(zhí)行以上命令就可以順利通過。
? ? 此時(shí)在執(zhí)行sys.getdefaultencoding()就會(huì)發(fā)現(xiàn)編碼已經(jīng)被設(shè)置為utf8的了,但是在解釋器里修改的編碼只能保證當(dāng)次有效,在重啟解釋器后,會(huì)發(fā)現(xiàn),編碼又被重置為默認(rèn)的ascii了,那么有沒有辦法一次性修改程序或系統(tǒng)的默認(rèn)編碼呢。
? ?
? ? 有兩種種方法設(shè)置python的默認(rèn)編碼:
方法一:在程序中加入以下代碼:
Python代碼
方法二:在python的Lib\site-packages文件夾下新建一個(gè)sitecustomize.py,內(nèi)容為:
Python代碼?
注意:sitecustomize.py這個(gè)文件最好不要使用記事本這樣的工具創(chuàng)建。
此時(shí)重啟python解釋器,執(zhí)行sys.getdefaultencoding(),發(fā)現(xiàn)編碼已經(jīng)被設(shè)置為utf8的了,
多次重啟之后,效果相同,這是因?yàn)橄到y(tǒng)在python啟動(dòng)的時(shí)候,自行調(diào)用該文件,設(shè)置系統(tǒng)的默認(rèn)編碼,
而不需要每次都手動(dòng)的加上解決代碼,屬于一勞永逸的解決方法。
總結(jié)
以上是生活随笔為你收集整理的‘ascii‘ codec can‘t encode characters in position的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【XSY3048 】Polynomina
- 下一篇: C# task和timer实现定时操作