剛開始學習python,須要在Python中註釋中文和輸出中文,如今開始嘗試;python
僅爲初步學習參考,高手請繞行。函數
-----------------------------------------------------------------------學習
第一步:在代碼中輸入如下命令,執行:編碼
#在Python中顯示中文註釋和輸出中文
a ="中文"
print aspa
返回錯誤:命令行
d:\Python27\python.exe "D:\test\中文.py"
Process started >>>
File "D:\test\中文.py", line 1
SyntaxError: Non-ASCII character '\xe5' in file D:\test\中文.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
<<< Process finished. (Exit code 1)
================ READY ================code
第二步,加入編碼格式:utf-8
#-*- coding:utf-8 –*-it
#在Python中顯示中文註釋和輸出中文
a ="中文"
print atest
返回結果:
d:\Python27\python.exe "D:\test\中文.py"
Process started >>>
涓枃
<<< Process finished. (Exit code 0)
================ READY ================
程序能夠正確執行,但輸出的還是亂碼。
第三步,查找亂碼並處理:
緣由:這是由於win的,命令行用的是cp936編碼,而上面腳本用的是utf-8編碼,所以致使亂碼。
解決方法是,使用decode和encode函數對字符從新解碼和編碼。
#-*- coding:utf-8 –*-
#在Python中顯示中文註釋和輸出中文
a ="中文"
print a.decode('utf-8').encode('cp936')
返回結果:
d:\Python27\python.exe "D:\test\中文.py"
Process started >>>
中文
<<< Process finished. (Exit code 0)
================ READY ================