Python 使用 UTF-8 編碼
版權信息: 可以任意轉載, 轉載時請務必以超鏈接形式標明文章原文出處, 即下面的聲明.
原文出處:http://blog.chenlb.com/2010/01/python-use-utf-8.html
一般我喜歡用 utf-8 編碼,在 python 怎麼使用呢?
1、在 python 源碼文件中用 utf-8 文字。一般會報錯,如下:
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 文件前面加編碼註釋,如:
- #!/usr/bin/python2.6
- # -*- coding: utf-8 -*-
- print "你好"
2、
python 對 url encode UTF-8 怎麼做呢?
windows 的命令行參數轉 utf-8 怎麼做呢?
代碼:
- # -*- coding: utf-8 -*-
- import urllib
- import sys
- if __name__ == '__main__':
- if len(sys.argv) > 1:
- str = sys.argv[1]
- str = unicode(str, 'gbk')
- else:
- str = "中文"
- print str
- params = {}
- params['name'] = str.encode("UTF-8")
- print urllib.urlencode(params)
python 內部是用 unicode 吧。
由於 windows 的命令行輸入的是 GBK 編碼的,可以要先轉爲 unicode(第三8行)。
要轉 url encode 時,先把 str 轉爲 utf-8。
默認的輸出結果:
中文
name=%E4%B8%AD%E6%96%87
寫 python 腳本來做寫小事情方便,比如要取些 solr 的數據,solr 的 url 編碼是 utf-8 的。