Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Ι'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...

like image 965
Antoni4040 Avatar asked Aug 08 '12 13:08

Antoni4040


People also ask

How do I fix UnicodeEncodeError in Python?

Only a limited number of Unicode characters are mapped to strings. Thus, any character that is not-represented / mapped will cause the encoding to fail and raise UnicodeEncodeError. To avoid this error use the encode( utf-8 ) and decode( utf-8 ) functions accordingly in your code.


3 Answers

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).

like image 190
Martijn Pieters Avatar answered Oct 08 '22 08:10

Martijn Pieters


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

import sys
reload(sys)
sys.setdefaultencoding('utf8')
like image 25
blueman010112 Avatar answered Oct 08 '22 08:10

blueman010112


teext = self.tableWidget.item(row, col).text().decode('utf-8')

Replace 'utf-8' with encoding of your text

like image 24
Daniil Ryzhkov Avatar answered Oct 08 '22 08:10

Daniil Ryzhkov