2012-12-20 44 views
1

我正在處理一些字符串操作並嘗試將它們放入數據庫。然後,我遇到了這個(我相信這是德國):django/python:python如何編碼非英文字符

Sichere Administration von VoIP-Endgeräten 

我把它放到數據庫後,我意識到,非英語字符變成了:

Sichere Administration von VoIP-Endger\u00e4ten 

;當我從數據庫中提取,並將該字符串傳遞給subprocess.Popen(),它給出錯誤:

TypeError: execv() arg 2 must contain only strings 

我的問題是:這是怎麼發生的?還有誰有任何有關如何學習編碼/解碼的東西有用的參考?謝謝。

回答

1

是的,閱讀Python Unicode HOWTO;你正在處理編碼和unicode文本。

第一個字符串是UTF-8的數據被解釋爲Latin-1的,第二個字符串是Unicode字符串,並且不能被傳遞到Popen()沒有首先編碼:

>>> print u'\u00e4' # A unicode escape code for the latin-1 character ä 
ä 
>>> u'\u00e4'.encode('utf8') # The same character encoded to UTF-8 
'\xc3\xa4' 
>>> print u'\u00e4'.encode('utf8').decode('latin1') # Misinterpreted as Latin-1 
ä 

你需要弄清楚在將您的數據傳遞到.Popen()之前,您的外部流程可以處理哪些編碼並調用.encode()