2012-12-20 40 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()