python 中文編碼

2021-07-09 21:48:54 字數 908 閱讀 8267

1.在python原始碼裡出現了中文

在原始碼開頭加上字元編碼的宣告,用乙個特殊的注釋行來定義字符集。

比如# -*- coding: utf-8 -*#encode=utf-8

2.操作中文字元

python中有兩種預設的字串:str和unicode,將字串看作是位元組序列,將字串看作是字元的序列。python內部使用的unicode編碼,decode是將普通字串按照引數中的編碼格式進行解析,生成unicode物件;encode是將unicode物件轉換成引數中編碼格式的普通字串。

str—>unicode :decode(『utf-8』)

unicode—>str :encode(『utf-8』)

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

json.loads()json.dumps()json.dumps()把python原始型別編碼成json型別;json.loads()把json型別解碼成python原始型別

當str包含中文,用json.dumps()方法編碼報錯時

import json

jsonstr = json.loads(str)

resultstr = json.dumps(jsonstr, ensure_ascii=false)

#resultstr = json.dumps(jsonstr, ensure_ascii=false, encoding='utf-8').encode('utf-8')

Python 中文編碼

python 檔案中如果未指定編碼,在執行過程會出現報錯 usr bin python print 你好,世界 以上程式執行輸出結果為 file test.py line 2 syntaxerror non ascii character xe4 in file test.py on line 2,...

Python 中文編碼

在python中如果輸出中文字元 你好,世界 就有可能會碰到中文編碼問題。python 檔案中如果未指定編碼,在執行過程會出現報錯 usr bin python print 你好,世界 以上程式執行輸出結果為 file test.py line 2syntaxerror non ascii char...

Python 中文編碼

python預設的編碼格式是ascii格式,在沒有修改編碼格式時是無法正確列印漢字的,所以在讀取中文時會報錯。解決方法是只要在檔案開頭加入 coding utf 8 或者 coding utf 8就行了 python 3.x原始碼檔案預設使用utf 8編碼,所以可以正常解析中文,無需指定utf 8。...