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 的內容:

 
  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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM