在python 下面一個包含中文字符串的列表(list)或字典,直接使用print會出現以下的結果:
>>> dict = {"asdf": "我們的python學習"}
>>> print dict
{'asdf': '\xe6\x88\x91\xe4\xbb\xac\xe7\x9a\x84python\xe5\xad\xa6\xe4\xb9\xa0'}
在輸出處理好的數據結構的時候很不方便,需要使用以下方法進行輸出:
>>> import json
>>> print json.dumps(dict, encoding="UTF-8", ensure_ascii=False)
{"asdf": "我們的python學習"}
注意上面的兩個參數
如果是字符串,直接輸出或者
print str.encode("UTF-8")
對於其他的編碼同樣使用。趕快試試吧。
# 從 str 轉換成 unicode print s.decode('utf-8') # 從 unicode 轉換成 str print u.encode('utf-8')