Python 中文編碼

2021-10-25 10:59:24 字數 1194 閱讀 3110

前面章節中我們已經學會了如何用 python 輸出 「hello, world!」,英文沒有問題,但是如果你輸出中文字元 「你好,世界」 就有可能會碰到中文編碼問題。

python 檔案中如果未指定編碼,在執行過程會出現報錯:

#!/usr/bin/python

print ("你好,世界")

以上程式執行輸出結果為:

file "test.py", line 2 syntaxerror: non-ascii character '\xe4' in file test.py on line 2, but no encoding declared; see for details

python中預設的編碼格式是 ascii 格式,在沒修改編碼格式時無法正確列印漢字,所以在讀取中文時會報錯。

解決方法為只要在檔案開頭加入# -*- coding: utf-8 -*-或者# coding=utf-8就行了

注意:# coding=utf-8的 = 號兩邊不要空格。

#!/usr/bin/python

#-*- coding: utf-8 -*-

print( "你好,世界" )

輸出結果為:

你好,世界

注意:python3.x 原始碼檔案預設使用utf-8編碼,所以可以正常解析中文,無需指定 utf-8 編碼。

注意:如果你使用編輯器,同時需要設定 py 檔案儲存的格式為 utf-8,否則會出現類似以下錯誤信

息:

syntaxerror: (unicode error) 『utf-8』 codec can』t decode byte 0xc4 in position 0:

invalid continuation byte

pycharm 設定步驟:

進入 file > settings,在輸入框搜尋 encoding。

找到 editor > file encodings,將 ide encoding 和 project encoding 設定為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 中文編碼

1.在python原始碼裡出現了中文 在原始碼開頭加上字元編碼的宣告,用乙個特殊的注釋行來定義字符集。比如 coding utf 8 或 encode utf 8 2.操作中文字元 python中有兩種預設的字串 str和unicode,將字串看作是位元組序列,將字串看作是字元的序列。python內...