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)
free_form_request
encode
-d byte string usingutf-8
encoding. works becauseutf-8
can represent[exid(이엑스아이디)] 위아래 (up&down) mv
.- however, format string (
'{ts}: free form request {free_form_request} requested {nick}'
) unicode string (because of importedfrom __future__ import unicode_literals
). - 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). - python attempts
decode
-ing using default encoding,ascii
, , fails, because byte stringutf-8
byte string includes byte values don't make sense inascii
. - 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
Post a Comment