파이썬

[python] 바이트를 문자열로 변환

zooheon 2022. 8. 21. 22:55
반응형

외부 프로그램의 표준 출력을 bytes개체로 캡처했습니다.

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'

다음과 같이 인쇄할 수 있도록 일반 Python 문자열로 변환하고 싶습니다.

>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2

방법을 시도했지만 binascii.b2a_qp()동일한 bytes개체를 다시 얻었습니다.

>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'

bytes개체를 strPython 3 으로 어떻게 변환 합니까?

 

bytes객체 를 디코딩하여 문자열을 생성합니다.

>>> b"abcde".decode("utf-8") 
'abcde'

위의 예 에서는 공통 인코딩이기 때문에 개체가 UTF-8 이라고 가정 합니다 . bytes그러나 데이터가 실제로 있는 인코딩을 사용해야 합니다!

 

바이트 문자열을 디코딩하여 문자(유니코드) 문자열로 변환합니다.


파이썬 3:

encoding = 'utf-8'
b'hello'.decode(encoding)

또는

str(b'hello', encoding)

파이썬 2:

encoding = 'utf-8'
'hello'.decode(encoding)

또는

unicode('hello', encoding)

 

이것은 바이트 목록을 문자열로 결합합니다.

>>> bytes_data = [112, 52, 52]
>>> "".join(map(chr, bytes_data))
'p44'

 

반응형