2011-06-28 92 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)