python 2.7 한글 UnicodeEncodeError, UnicodeDecodeError 해결하기
python 2.7 한글 UnicodeEncodeError, UnicodeDecodeError 해결하기
사용환경 : windows 7 64bit, python 2.7.9 64bit
1. 한글 unicode -> 한글 str 변환시 :
str(k) ==> encode error 발생.
>>> str(unicode('한글','euc-kr'))
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
str(unicode('한글','euc-kr'))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
>>>
----------> 해결책
>>> print str(unicode('한글','euc-kr').encode('euc-kr'))
한글
>>>
2. 한글 str -> 한글 unicode 변환시 :
unicode(k) ==> decode error 발생.
>>> unicode('한글')
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
unicode('한글')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 0: ordinal not in range(128)
>>>
----------> 해결책
>>> print unicode('한글','euc-kr')
한글
>>>
3. 영문 unicode + 한글 str ==> decode error 발생.
>>> u'abc' + '한글'
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
u'abc' + '한글'
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 0: ordinal not in range(128)
>>>
----------> 해결책
>>> print str(u'abc') + '한글' # 모두 str type으로 바꾸거나
abc한글
또는
>>> print u'abc' + unicode('한글','euc-kr') # 모두 unicode type으로 바꾼다.
abc한글
4. 영문 unicode + 영문 str ==> 영문 unicode 정상변환
>>> u'abc' + 'abc'
u'abcabc'
>>>
5. 한글 unicode + 영문 str => unicode 정상변환
>>> 'abc' + unicode('한글','euc-kr')
u'abc\ud55c\uae00'
>>> print 'abc' + unicode('한글','euc-kr')
abc한글