Python 2.7.6 + unicode_literals - UnicodeDecodeError: 'ascii' codec can't decode byte -


i'm trying print following unicode string i'm receiving unicodedecodeerror: 'ascii' codec can't decode byte error. can please form query can print unicode string properly?

>>> __future__ import unicode_literals >>> ts='now' >>> free_form_request='[exid(이엑스아이디)] 위아래 (up&down) mv' >>> nick='me'  >>> print('{ts}: free form request {free_form_request} requested {nick}'.format(ts=ts,free_form_request=free_form_request.encode('utf-8'),nick=nick))  traceback (most recent call last):   file "<stdin>", line 1, in <module> unicodedecodeerror: 'ascii' codec can't decode byte 0xec in position 6: ordinal not in range(128) 

thank in advance!

here's happen when construct string:

'{ts}: free form request {free_form_request} requested {nick}'.format(ts=ts,free_form_request=free_form_request.encode('utf-8'),nick=nick) 
  1. free_form_request encode-d byte string using utf-8 encoding. works because utf-8 can represent [exid(이엑스아이디)] 위아래 (up&down) mv.
  2. however, format string ('{ts}: free form request {free_form_request} requested {nick}') unicode string (because of imported from __future__ import unicode_literals).
  3. you can't use byte strings format arguments unicode string, python attempts decode byte string created in 1. create unicode string (which valid format argument).
  4. python attempts decode-ing using default encoding, ascii, , fails, because byte string utf-8 byte string includes byte values don't make sense in ascii.
  5. python throws unicodedecodeerror.

note while code doing here, not throw exception on python 3, instead substitute repr of byte string (the repr being unicode string).


to fix issue, pass unicode strings format.

that is, don't step 1. encoded free_form_request byte string: keep unicode string removing .encode(...):

'{ts}: free form request {free_form_request} requested {nick}'.format(     ts=ts,      free_form_request=free_form_request,      nick=nick) 

note padraic cunningham's answer in comments well.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -