Search code examples
pythoncharacter-encoding

Error print special character on results with Flask-SQLAlchemy


def shows():
    with Operator.app.app_context():
        u = Operator.db.session.query(Operator.Subject).all()
        for index, row in enumerate(u):
            print(row.complete)

===============================INCOMPLETE RESULTS

the values are printed until it encounters special characters as shown in the code

.
.
.
HERRERA HERNANDEZ SONIA EUSEBIA
MEDINA FLORES TANIA MARISABETH
MEZARINO TARAZONA JORK LEE MICHAEL
VALLES MENDIETA WASHINTON
REYNALTE BRIOSO MARY LUZ
Exception in Tkinter callback
Traceback (most recent call last):
  File "c:\users\intel\appdata\local\programs\python\python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "<string>", line 11, in login
  File "C:\Program Files (x86)\ActiveState Komodo IDE 12\lib\support\dbgp\bin\py3_dbgp.py", line 129, in write
    self._origStream.write(s)
  File "c:\users\intel\appdata\local\programs\python\python310\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x91' in position 10: character maps to <undefined>

========================================= BUT

when i modify my code like this

def shows():
    with Operator.app.app_context():
        u = Operator.db.session.query(Operator.Subject).all()
        for index, row in enumerate(u):
            print(row.complete.encode("utf-8"))

===============================COMPLETE RESULTS

this way, results with strange characters

.
.
.
b'HERRERA HERNANDEZ SONIA EUSEBIA'
b'MEDINA FLORES TANIA MARISABETH'
b'MEZARINO TARAZONA JORK LEE MICHAEL'
b'VALLES MENDIETA WASHINTON'
b'REYNALTE BRIOSO MARY LUZ'
b'RIVERA PE\xc3\x83\xc2\x91A HERNAN ANTONIO'
b'RIVERA PE\xc3\x83\xc2\x91A JOSE LUIS'
b'JACINTO PINGO OLGA'
b'AGUIRRE PE\xc3\x83\xc2\x83\xc3\x82\xc2\x91A GEINER'
b'CARBAJAL PE\xc3\x83\xc2\x91A EDISON'
b'CARRERA PE\xc3\x83\xc2\x91A ERIKA'
b'PI\xc3\x91AN PEZO ALBA PATRICIA'
b'PI\xc3\x91AN PORRAS JOAQUIN'

Solution

  • The output contains characters that cannot be decoded by your terminal's encoding (cp1252). Change your terminal's encoding to UTF-8. Have a look at this and this. If you are printing to your IDE's terminal you'll need to consult your IDE's documentation.

    Source: This was originally posted as a comment by snakecharmerb