[Python] Cannot Split, A bytes-like object is required, not ‘str’
Python에서 split method를 사용하던 중 다음과 같은 error가 발생했다.
def doSplit():
my_str = b"Hello World"
my_str.split(" ")
if __name__ == "__main__":
doSplit()
Traceback (most recent call last):
File "main.py", line 7, in
doSplit()
File "main.py", line 3, in doSplit
my_str.split(" ")
TypeError: a bytes-like object is required, not 'str'
원인은 문자열의 형태가 맞지 않아서 발생했다. Python에서 문자열의 형태는 String과 Bytes 타입으로 구분된다. 각 관계는 아래처럼 나타낼 수 있다.
- String –> DECODING –> Bytes
- Bytes –> ENCODING –> String
text = "Hello" # text is string type
text_byte = text.encode('utf-8') # text_byte is byte type
text_str = text_byte.decode('utf-8')# text_str is string type
따라서 위 문제를 해결하기 위해서 다음과 같이 수정해주면 된다.
def doSplit():
my_str = b"Hello World"
my_str.split(b" ")
if __name__ == "__main__":
doSplit()
Reference
- https://euriion.com/?p=412627
- https://stackoverflow.com/questions/50829364/cannot-split-a-bytes-like-object-is-required-not-str