5

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?

2 Answers 2

8

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

unicode(YOUR_QSTRING_STRING)
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.