xinster
xinster

Reputation: 21

ChineseWords python format UnicodeEncodeError , but in django OK

demo code like this:

#_*_ coding: utf-8 _*_
a = u'北京'
b = u'地图'
c = '{0} {1}'.format(a, b)

when i write this in python file(test.py), and then run 'python test.py'. it will raise Exception like:

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

but, when i run a Django, django methon run demo code, it will be ok。

django run demo code

    python version and python path is totally same.
    python version: 2.7.9

Upvotes: 1

Views: 63

Answers (2)

xinster
xinster

Reputation: 21

defaultencoding has changed:

import sys
reload(sys)
sys.setdefaultencoding('utf8')

Upvotes: 1

Erik Cederstrand
Erik Cederstrand

Reputation: 10220

In Python 2.7, the format string also needs to be unicode:

Python 2.7.6 (default, Nov 23 2017, 15:49:48) 
>>> '{}'.format(u'æ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe6' in position 0: ordinal not in range(128)
>>> u'{}'.format(u'æ')
u'\xe6'

Your Django example may work because it imports unicode_literals somewhere, which will tell the interpreter to see 'foo' as u'foo' instead of the default b'foo':

Python 2.7.6 (default, Nov 23 2017, 15:49:48) 
>>> from __future__ import unicode_literals
>>> '{}'.format(u'æ')
u'\xe6'
>>> u'{}'.format(u'æ')
u'\xe6'

Upvotes: 3

Related Questions