0

sorry for my bad english. I have some code:

import csv, pyodbc
MDB = 'base.mdb'
DRV = '{Microsoft Access Driver (*.mdb)}'
PWD = 'pw'
con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV, MDB, PWD))
cur = con.cursor()
SQL = 'SELECT * FROM Units;' # your query goes here
rows = cur.execute(SQL).fetchall()
for row in rows:
    for r in row:
        print str(r)
cur.close()
con.close()

When i am executing this i have traceback:

print str(r)

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

How can i convert this symbolst to string. Thank you for help.

Valeriy Gaydar
  • 500
  • 1
  • 6
  • 26
  • http://docs.python.org/2/library/stdtypes.html#str.decode check there and http://docs.python.org/2/library/stdtypes.html#str.encode – Mike McMahon Dec 16 '13 at 16:38
  • print str(r).encode("utf-8") UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) – Valeriy Gaydar Dec 16 '13 at 16:41
  • print str(r).encode("utf-8") UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) – Valeriy Gaydar Dec 16 '13 at 16:42

1 Answers1

0
r.encode('utf-8')

or possibly

unicode(r)

The unicode() constructor has the signature unicode(string[, encoding, errors]). All of its arguments should be 8-bit strings. The first argument is converted to Unicode using the specified encoding; if you leave off the encoding argument, the ASCII encoding is used for the conversion, so characters greater than 127 will be treated as errors:

EDIT: so the problem is the terminal you are outputting to doesn't support those characters (UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function) and your best option may be to replace the characters outside of the acceptable range.

If you remove the print statement or simply just go ahead and manipulate the data things will proceed without issue (python can handle the strings internally).

If you're worried things aren't looking right try pushing your content to a file encoded with the proper encoding (UTF-8 or UTF-16 should handle the russian characters).

Community
  • 1
  • 1
Mike McMahon
  • 7,096
  • 3
  • 30
  • 42