繁体   English   中英

QString: Unicode 编解码问题

[英]QString: Unicode encoding-decoding problem

我正在尝试将 Unicode 字符串简单转换为标准字符串,但没有成功。

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

我想要: '\xc5\x9f'通知 str 类型不是 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'

你知道更好的方法吗?

如果您有 QString 数据类型的 unicode 字符串,并且需要将其转换为 python 字符串,您只需:

unicode(YOUR_QSTRING_STRING)

这就是你所追求的吗?

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'>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM