wwli
wwli

Reputation: 2681

python string unicode issue

Here is my code (I am using python 2.7 )

    result = " '{0}' is unicode or something: ".format(mongdb['field'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in position 27: ordinal not in range(128)

It looks like a string I read from mongodb contains unicode. And it throws this error. How to fix it to concatenate this unicde with custom string 'is unicode or something:' ?

Thanks in advance

UPDATE

result = u" '{0}' is unicode or something: ".format(mongdb['field']) 

works for me

Upvotes: 2

Views: 4462

Answers (2)

zwol
zwol

Reputation: 140786

You have to know what encoding the text coming out of MongoDB is actually in. \xB0 suggests Windows-1252 instead of UTF-8, so try this:

 result = ("'{0}' is unicode or something"
           .format(mongdb['field'].decode('windows-1252'))

Upvotes: 1

Thomas Orozco
Thomas Orozco

Reputation: 55293

Use a unicode format string (recommended):

result = u" '{0}' is unicode or something: ".format(mongdb['field'])

Or encode the field:

result = " '{0}' is unicode or something: ".format(mongdb['field'].encode('utf-8'))

Upvotes: 9

Related Questions