2011-06-28 93 views
4

我想做一个简单的Unicode字符串转换为标准字符串,但没有成功。QString:Unicode编码 - 解码问题

我:PyQt4.QtCore.QString(u'\xc5\x9f')

我想:'\xc5\x9f'通知STR类型不是Unicode,是因为我使用的库不接受统一。

这里是我试过了,你可以看到我是多么绝望是:):

>>> s = QtCore.QString(u'\xc5\x9f') 
>>> str(s) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) ' 
>>> s.toUtf8() 
PyQt4.QtCore.QByteArray('\xc3\x85\xc2\x9f') 
>>> s.toUtf8().decode("utf-8") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'QByteArray' object has no attribute 'decode' 
>>> str(s.toUtf8()).decode("utf-8") 
u'\xc5\x9f' 
>>> str(str(s.toUtf8()).decode("utf-8")) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) 

我知道有很多关于Unicode的问题,但我不能找到这个答案。

我该怎么办?

编辑:

我发现了一个哈克的方式:

你知道更好的办法?

回答

3

这是你在追求什么?

In [23]: a 
Out[23]: u'\xc5\x9f' 

In [24]: a.encode('latin-1') 
Out[24]: '\xc5\x9f' 

In [25]: type(a.encode('latin-1')) 
Out[25]: <type 'str'> 
+0

究竟是:)。谢谢。 – utdemir

7

如果你有QString的数据类型的Unicode字符串,并且需要将其转换为Python字符串,你只是:

unicode(YOUR_QSTRING_STRING)