본문 바로가기

Python

파이썬(Python) 문자 인코딩 이해하기

이번 글에서는 파이썬을 그동안 사용하면서 많이 쓰이는 문자 인코딩에 대해서 작성하고자 합니다.

문자 인코딩이란 위키백과를 참고하면 사용자가 입력한 문자나 기호들을 컴퓨터가 이용할 수 있는 신호로 만드는 것을 말합니다.

ASCII(아스키코드)를 시작으로, UTF-8, EUC-KR, cp949 등 다양한 문자 인코딩 방법이 있습니다.

많이 들어본 유니코드는 국제표준 문자표이며, UTF-8은 유니코드를 사용한 인코딩 방식입니다.

(*Jeong Dowon 님의 블로그 글 중 "Unicode와 UTF-8 간단히 이해하기 참조")

 

Python2에서는 ASCII가 디폴트 인코딩 방법으로 되어있습니다.

### Python 2 ###

import sys
print(sys.getdefaultencoding())

>>> ascii

 

따라서, 코드에서 한글을 사용할 때(ASCII코드는 한글을 표현할 수 없습니다.)

# -*- coding: utf-8 -*-

와 같이 파일의 인코딩 형태를 코드 맨 윗줄에 따로 명시하는 이유이기도 합니다.

### Python2 ###

import sys
print(sys.getdefaultencoding())

print("한글")

>>> SyntaxError: Non-ASCII character '\xed' in file test.py on line 5, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

 

### Python2 ###

# -*- coding: utf-8 -*-

import sys
print(sys.getdefaultencoding())

print("한글")

>>> ascii
>>> 한글

 

Python3에서는 UTF-8이 디폴트 인코딩 방법으로 되어있으므로 따로 명시하지 않으셔도 한글을 사용할 수 있습니다.

### Python3 ###

import sys
print(sys.getdefaultencoding())

print("한글")

>>> utf-8
>>> 한글

 

또한 UTF-8이 디폴트 인코딩 방법이기 때문에 모든 문자열은 유니코드로 처리됩니다.

따라서 Python2에서는 구분되었던 "한글", u"한글"이 Python3에서는 동일하게 처리됩니다.

(*가급적 Python3를 사용하는것이 건강에 좋을 것 같습니다.)

### Python2 ###

# -*- coding: utf-8 -*-
import sys

_string = "한글"
_unicode = u"한글"

print(_string)
print(type(_string))
print(_unicode)
print(type(_unicode))

# unicode to utf-8
print(_unicode.encode('utf-8'))
print(type(_unicode.encode('utf-8')))

# 결과
한글
<type 'str'>
한글
<type 'unicode'>
한글
<type 'str'>

 

### Python3 ###

import sys

_string = "한글"
_unicode = u"한글"

print(_string)
print(type(_string))
print(_unicode)
print(type(_unicode))

# 결과
한글
<class 'str'>
한글
<class 'str'>

 

이제 Python3에서 자주 쓰는 문자 인코딩 예를 보겠습니다.

아래 코드에서는 chardet.detect() 함수를 사용하여 인코딩을 추정하였습니다.

import sys
import chardet

# _string은 현재 유니코드
_string = "한글"
print(_string, type(_string))

# UTF-8 예시
encoded_string = _string.encode('utf-8')
print(encoded_string, type(encoded_string))
print(chardet.detect(encoded_string))

# EUC-KR 예시
encoded_string = _string.encode('euc-kr')
print(encoded_string, type(encoded_string))
print(chardet.detect(encoded_string))

# cp949 예시
encoded_string = _string.encode('cp949')
print(encoded_string, type(encoded_string))
print(chardet.detect(encoded_string))

# 결과
한글 <class 'str'>

b'\xed\x95\x9c\xea\xb8\x80' <class 'bytes'>
{'encoding': 'utf-8', 'confidence': 0.7525}

b'\xc7\xd1\xb1\xdb' <class 'bytes'>
{'encoding': 'windows-1252', 'confidence': 0.73}

b'\xc7\xd1\xb1\xdb' <class 'bytes'>
{'encoding': 'windows-1252', 'confidence': 0.73}

위와같이 인코딩 기능을 사용하여 문자를 바이트로 표현하는 예를 보았습니다.

뭔가 글이 잡다하지만 오늘은 여기까지.

감사합니다.