Question


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.

Was it helpful?

Solution

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!

OTHER TIPS

try following:

  1. add # -*- coding: utf-8 -*- magic comment at the begging of your script (details here)
  2. use "u" string declaration with your string constant

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top