python 使用 UTF-8 編碼

題記

通常我喜歡用 utf-8 編碼,在 python 怎麼使用呢?html

使用utf-8 文字

在 python 源碼文件中用 utf-8 文字。通常會報錯,以下:python

File "F:\workspace\psh\src\test.py", line 2
SyntaxError: Non-ASCII character '\xe4' in file F:\workspace\psh\src\test.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

test.py 的內容:編碼

print "你好"

若是要正常運行在 test.py 文件前面加編碼註釋,如:spa

#!/usr/bin/python2.6  
# -*- coding: utf-8 -*-  
print "你好"

或者加入:code

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

更多入門教程能夠參考:(http://www.bugingcode.com/python_start/)htm

相關文章
相關標籤/搜索