Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags more
Archives
Today
Total
관리 메뉴

-

PYTHON UTF-8 decoding 본문

카테고리 없음

PYTHON UTF-8 decoding

푸른파랑 2019. 11. 18. 16:56

로그를 처리하다 보니, utf-8로 encoding된 문자열 자체를 처리할 경우가 있었다.

 

단순히 decoding하면 될꺼라 생각했었는데,, 생각보다 잘 안되어서 정리한다.

 

Pyhton 2.x

def decode_str(self,raw):
    try:
        result = raw.decode('string-escape').decode("utf-8")
    except:
        result = raw
    return result

Python 3.x ( 3.x는 기본 인코딩이 utf-8이고, str에서 decode, encode가 없어졌다,,,)

def string_escape(s, encoding='utf-8'):
    return (s.encode('latin1')         # To bytes, required by 'unicode-escape'
             .decode('unicode-escape') # Perform the actual octal-escaping decode
             .encode('latin1')         # 1:1 mapping back to bytes
             .decode(encoding))        # Decode original encoding

역쉬 stackOverflow에는 나같은 사람도 많고, 고수도 많은 듯 하다,,,

https://stackoverflow.com/questions/14820429/how-do-i-decodestring-escape-in-python3