Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QString: Unicode encoding-decoding problem

Tags:

python

pyqt

I am trying to make a simple conversion to Unicode string to standart string, but no success.

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

I want: '\xc5\x9f' notice str type not unicode, because the library I am using is not accepting unicode.

Here is what I tried, you can see how hopeless I am :) :

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

I know there are a lot of questions related to Unicode, but I can't find this answer.

What should I do?

Edit:

I found a hacky way:

>>> unicoded = str(s.toUtf8()).decode("utf-8")
>>> unicoded
u'\xc5\x9f'
>>> eval(repr(unicoded)[1:])
'\xc5\x9f'

Do you know a better way?

like image 382
utdemir Avatar asked Jun 28 '11 21:06

utdemir


2 Answers

If you have unicode string of QString data type , and need to convert it to python string , you just :

unicode(YOUR_QSTRING_STRING)
like image 188
PersianGulf Avatar answered Sep 28 '22 08:09

PersianGulf


Is this what you are after?

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'>
like image 36
Fredrik Pihl Avatar answered Sep 28 '22 06:09

Fredrik Pihl