Reputation: 626
I do not managed to simply print a QString variable containing a special character.
I always get a UnicodeEncodeError:
'ascii' codec can't encode characters in position ....
Here is the code I tried without success :
var1 = "éé" #idem with u"éé"
var2 = QString (var1)
print var2
--->>> UnicodeEncodeError
print str(var2)
--->>> UnicodeEncoreError
var3 = QString.fromLocal8Bit (var1) #idem with fromLatin1 and fromUtf8
print var3
--->>> UnicodeEncodeError
codec = QTextCodec.codecForName ("UTF-8") #idem with ISO 8859-1
var4 = codec.toUnicode (var2.toUtf8().data()) #idem with toLatin1 instead of toUtf8
print var4
--->>> UnicodeEncodeError
I also tried to use :
QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8"))
I really need to print a QString variable, not a QByteArray or other object.
Upvotes: 4
Views: 10947
Reputation: 20492
try following:
# -*- coding: utf-8 -*-
magic comment at the begging of your script (details here)below is an example which works for me
# -*- coding: utf-8 -*-
from PyQt4 import QtCore
var1 = u"éé" #idem with u"éé"
print var1
var2 = QtCore.QString(var1)
print var2
var3 = QtCore.QString(u"éé")
print var3
returns:
éé
éé
éé
hope this helps, regards
Upvotes: 1
Reputation: 99490
It works for me using toUtf8()
:
>>> s = u'éé'
>>> qs = QString(s)
>>> qs
PyQt4.QtCore.QString(u'\xe9\xe9')
>>> print qs
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)
>>> print qs.toUtf8()
éé
>>>
Your internal data should be Unicode, so you should be using u'éé'
rather than just 'éé'
as you stated in your in your question. Your comment even says u'éé'
.
Update: Sorry, but printing or str()
on Unicode cannot be guaranteed to work on Unicode objects unless you use a specific encoding. Print streams accept byte arrays/bytestrings, and str() on a Unicode object is effectively trying to convert Unicode to a byte array/bytestring. You're not going to be able to avoid byte arrays!
Upvotes: 5