deltanovember
deltanovember

Reputation: 44051

Why am I getting an error trying to print a string in Python 2.7?

I'm trying to use

https://pypi.python.org/pypi/dbf

To read a database file. I'm trying to print the records as follows:

for record in race_db:
    print record

This gives me an error message

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc9 in position 4: ordinal not in range(128)

So I tried to map to unicode

string_record = [unicode(item) for item in record]

same thing. utf-8:

string_record = [unicode(item, "utf8") for item in record]

TypeError: coercing to Unicode: need string or buffer, datetime.date found

I just want some to sort tostring functionality what am I doing wrong? I know I can successfully loop through all the records because something like:

print 'blah'

works fine. It's just something in the encoding is tripping me up.

Upvotes: 2

Views: 215

Answers (1)

Adam Rosenfield
Adam Rosenfield

Reputation: 400224

The single byte \xC9 is not a valid encoding of anything in UTF-8. You need to figure out how the text is currently encoding—in this case, it's most likely either ISO 8859-1 or Windows-1252. Then, decode it accordingly.

For example, if it's Windows-1252, you'd decode it as follows:

string_record = 'foo \xc9 bar'
print string_record.decode('Windows-1252')  # Output: "foo É bar"

Upvotes: 4

Related Questions