QString: Unicode编码解码问题
我想把一个简单的Unicode字符串转换成标准字符串,但一直没成功。
我现在有:PyQt4.QtCore.QString(u'\xc5\x9f')
我想要的是:'\xc5\x9f'
,注意这里是字符串类型而不是Unicode,因为我用的库不支持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的问题,但我找不到这个答案。
我该怎么办呢?
补充:
我找到了一种比较“hacky”的方法:
>>> unicoded = str(s.toUtf8()).decode("utf-8")
>>> unicoded
u'\xc5\x9f'
>>> eval(repr(unicoded)[1:])
'\xc5\x9f'
你知道更好的方法吗?
2 个回答
8
如果你有一个QString类型的Unicode字符串,想把它转换成Python字符串,你只需要:
unicode(YOUR_QSTRING_STRING)
4
这就是你想要的吗?
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'>