python使用 UTF-8編碼

Python 使用 UTF-8 編碼

發表於:2010年1月28日 | 分類:Python | 標籤: utf8 | views(58,751)

版權信息: 可以任意轉載, 轉載時請務必以超鏈接形式標明文章原文出處, 即下面的聲明.

原文出處: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 的內容:

  1. print "你好"  

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

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

2、
python 對 url encode UTF-8 怎麼做呢?

windows 的命令行參數轉 utf-8 怎麼做呢?

代碼:

  1. # -*- coding: utf-8 -*-  
  2. import urllib  
  3. import sys  
  4.   
  5. if __name__ == '__main__':  
  6.     if len(sys.argv) > 1:  
  7.         str = sys.argv[1]  
  8.         str = unicode(str, 'gbk')  
  9.     else:  
  10.         str = "中文"  
  11.   
  12.     print str  
  13.     params = {}  
  14.     params['name'] = str.encode("UTF-8")  
  15.   
  16.     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 的。

參考:http://evanjones.ca/python-utf8.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章