문자열을 바이트로 변경하는 방법을 소개합니다.
- bytes()를 이용한 방법
- encode()를 이용한 방법
bytes()를 이용한 방법
bytes(string, encoding)
를 이용하여 string을 bytes로 변경할 수 있습니다. 변경하려는 encoding을 인자로 전달해주면 됩니다.
타입을 확인하면 bytes로 변경된 것을 볼 수 있습니다.
my_string = "Hello world, Python"
print(my_string)
result = bytes(my_string, 'utf-8')
print(result)
print(type(result))
Output:
Hello world, Python
b'Hello world, Python'
<class 'bytes'>
encode()를 이용한 방법
string.encode(encoding)
을 이용하여 byte로 변환할 수도 있습니다. encoding은 인자로 전달하면 됩니다.
my_string = 'Hello world, Python'
print(my_string)
result = my_string.encode('utf-8')
print(result)
print(type(result))
Output:
Hello world, Python
b'Hello world, Python'
<class 'bytes'>
decoding하는 방법
string.decode()를 이용한 방법
string.decode(encoding)
으로 bytes를 string으로 변환할 수 있습니다.
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
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 - 특정 문자열로 시작하는 문자열 찾기
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - bytes를 String으로 변환하는 방법
- Python - 문자열에서 특정 단어 추출
- Python - 문자열 뒤집기, 문자열 거꾸로 출력
- Python - 리스트가 비어있는지 확인
- Python - dictionary의 중복 제거 방법
- Python - 리스트 크기(size) 구하기
- Python - 2차원 리스트를 1차원 리스트로 만들기
- Python - 현재 날짜, 시간 가져오는 방법
- Python - 리스트 중복 제거