파이썬에서 문자열(String)을 바이트(byte)로 변환하는 방법을 소개합니다.
1. 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'>
2. 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'>
3. 바이트를 문자열로 변환
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'>
References
Loading script...
Related Posts
- Python 소수점 반올림, round() 예제
- 파이썬 주석 처리, 단축키 소개
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 정리 및 예제
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 디폴트 매개변수(Default parameters)
- Python - filter() 사용 방법 및 예제