byte_bytearray.py
한글 문자열을 byte 로 저장할껀데 표현 못하는 문자열은 무시하거나 다른 글자로 대체할 수 있다.
한글 문자열을 byte 형태로 변환하는 법
1byte 는 8bit 로 이진수로 0-255 로 표현이 가능하다. (16진수로 2 자리)
이때 bytes() 함수와 bytearray() 함수로 데이터를 byte 형태로 생성해낼 수 있다.
bytes()
인자로 전달된 문자열(string)이나 바이트(byte) 배열, 정수(integer)들을 이진 데이터로 변환하여 바이트(byte) 객체를 생성합니다. 이때, 생성된 바이트(byte) 객체는 변경 불가능(immutable)합니다
print('string, encoding, errors [ignore(''), replace(?)]')
print(bytes('한글', 'utf-8', 'replace'))
print(bytes('한글', 'utf-16', 'replace'))
print(bytes('한글', 'ascii', 'replace'))
print(bytes('한글', 'ascii', 'ignore'))
문자열, 인코딩할 방법, 에러처리를 인자로 바이트 데이터를 생성한다.
print(chr(0xc1), bytes(chr(0xc1), 'utf-8', 'replace'))
print(chr(0xc1), bytes (chr(0xc1), 'utf-8', 'ignore'))
print(bytes('Á', 'utf-8', 'replace'))
print(bytes('Á', 'utf-8', 'ignore'))
print(bytes(chr(0xc1)+'ngela', 'utf-8', 'ignore'))
print(bytes('Ángela', 'utf-8', 'replace'))
print(bytes('Ángela', 'ascii', 'replace'))
print(bytes('Ángela', 'ascii', 'ignore'))
우리가 인코딩할 수 없는 'Á' 같은 문자가 있을 때 이를 replace 로 ? 문자로 바꾸거나 ignore 로 공백으로 바꿀 수 있다.
#bytearray() is similar to bytes(), but mutable
bytearrstr = bytearray('Ángela', 'ascii', 'replace')
print(bytearrstr)
bytearrstr[0] = 65 # is ascii code of 'A'
print(bytearrstr)
#bytes() is immutable
bytestr = bytes('Ángela', 'ascii', 'replace')
print(bytestr)
try:
bytestr[0] = 65 # is ascii code of 'A'
print(bytestr)
except Exception as e:
print(e)
비슷한 bytearray() 함수는 byte 데이터를 생성해주지만 slicing 을 사용해 문자를 바꿀 수 있다.
하지만 bytes() 함수는 문자를 바꿀 수 없다.
try:
실행할 코드
except:
예외가 발생했을 때 처리하는 코드
예외처리를 하는 try except 를 사용해 bytes() 함수로 만든 바이트 데이터를 우리가 slicing 으로 바꾸려고 할 때 예외한 것을 확인할 수 있다.
bytearray()
bytes() 함수와 비슷하지만 생성된 바이트(byte) 객체가 변경 가능(mutable)합니다. 따라서, bytearray() 함수로 생성한 바이트(byte) 객체는 인덱싱(indexing)이나 슬라이싱(slicing) 등의 연산을 통해 내부 데이터를 수정할 수 있습니다.
'수업정리 > Fundamental' 카테고리의 다른 글
Python basic 4 - map(), import, zip() 한글을 입력하면 유니코드로 (0) | 2023.04.12 |
---|---|
Python basic 3 - 파일 open, write2file.py (0) | 2023.04.05 |
Python basic 2 - 수학 함수(all, max, min, sorted, pow)format, zip (0) | 2023.03.31 |
command 명령어 1 (0) | 2023.03.22 |
[Python] 한글 유니코드 (0) | 2023.03.17 |