utf-8
으로 encoding된 bytes를 String으로 다시 변환해야할 때가 있습니다.
bytes를 string으로 decoding하는 방법을 소개합니다.
- string.decode()를 이용한 방법
- str()을 이용한 방법
string.decode()를 이용한 방법
string.decode(encoding)
으로 bytes를 string으로 변환할 수 있습니다.
bytes가 encoding될 때 사용된 타입을 인자로 전달하면 됩니다.
# bytes
bytes = b'Hello world, Python'
print(bytes)
print(type(bytes))
# decode bytes to string
result = bytes.decode('utf-8')
print(result)
print(type(result))
Output:
b'Hello world, Python'
<class 'bytes'>
Hello world, Python
<class 'str'>
str()을 이용한 방법
str(bytes, encoding)
으로 bytes를 string으로 변환할 수 있습니다. bytes가 encoding될 때 사용된 타입을 인자로 전달하면 됩니다.
# bytes
bytes = b'Hello world, Python'
print(bytes)
print(type(bytes))
# decode bytes to string
result = str(bytes, 'utf-8')
print(result)
print(type(result))
Output:
b'Hello world, Python'
<class 'bytes'>
Hello world, Python
<class 'str'>
참고
Recommended Posts:
- Python - dict 정렬 (Key, Value로 sorting)
- Python - float을 int로 변경하는 방법
- Python - String을 bytes로 변경하는 방법
- Python - 특정 문자열로 시작하는 문자열 찾기
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 문자열에서 특정 단어 추출
- Python - 문자열 뒤집기, 문자열 거꾸로 출력
- Python - 리스트가 비어있는지 확인
- Python - dictionary의 중복 제거 방법
- Python - 리스트 크기(size) 구하기
- Python - 2차원 리스트를 1차원 리스트로 만들기
- Python - 현재 날짜, 시간 가져오는 방법
- Python - 리스트 중복 제거