Python
Python - bytes를 String으로 변환하는 방법
크라우니
2022. 6. 15. 14:21
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'>
참고 : https://codechacha.com/ko/python-convert-bytes-to-string/