UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128)
Asked Answered
M

3

6

Ι've tried all the solution that I could find, but nothing seems to work:

teext = str(self.tableWidget.item(row, col).text())

I'm writing in greek by the way...

Memory answered 8/8, 2012 at 13:26 Comment(0)
F
16

Clearly, self.tableWidget.item().text() returns Unicode, and you need to use the decode method instead:

self.tableWidget.item(row, col).text().encode('utf8')

You really want to review the Python Unicode HOWTO to fully appreciate the difference between a unicode object and it's byte encoding.

Another excellent article is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!), by Joel Spolsky (one of the people behind Stack Overflow).

Firstclass answered 8/8, 2012 at 13:28 Comment(3)
Well, i do not get errors any more, but when I'm writing teext to an .xls file, when I open the .xls file it shows nothing...Memory
Read the articles I included in my answer; you'll need to find out what encoding you need to use.Firstclass
teext = unicode(self.tableWidget.item(row, col).text()) seems to solve the problem... Anyway, thanks a lot for your help...Memory
P
2

Try put following code in the beginning
It's fixed my problem perfectly

import sys
reload(sys)
sys.setdefaultencoding('utf8')
Partite answered 1/4, 2018 at 7:26 Comment(0)
B
1
teext = self.tableWidget.item(row, col).text().decode('utf-8')

Replace 'utf-8' with encoding of your text

Blackett answered 8/8, 2012 at 13:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.