How can I print a QString containing a special character with python using PyQt?


I was unable to just print the QString variable containing the special character.
I always get UnicodeEncodeError:

'ascii' codec cannot 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 using:

 QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8"))  

I really need to print a QString variable, not a QByteArray or other object.

+3
source share
2 answers

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 use u'éé', not just 'éé'as you pointed out in your question. Your comment even says u'éé'.

: , str() Unicode Unicode, . /bytestrings, str() Unicode Unicode /bytestring. !

+5

:

  • # -*- coding: utf-8 -*- script ( )
  • "u"

- ,

# -*- 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

:

éé

Ee

Ee

, ,

+1

Source: https://habr.com/ru/post/1784086/


All Articles