[python] 터미날 수신 Byte 코드 변환 및 \n 제거

2020년 08월 24일 by 진아사랑해

    [python] 터미날 수신 Byte 코드 변환 및 \n 제거 목차
반응형

라즈베리파이 3B+에서 socat를 사용한 가상 시리얼 포트를 이용한 통신 프로그램을 작성중에

Python에 대한 이해 부족으로 약간의 시간을 소비하였다

1. 터미널에서 수신한 메시지 

   b'222\n'

2. type(b'222\n')

   <class 'bytes'>

   유니코드가 아니라 bytes 코드이다

   (bytes는 원시 이진 데이터로 사용되어지거나 1바이트 문자로 고정을 위해 사용되어집니다.)

3. 맨 뒤에 붙은 \n을 제거하기 위한 작업

1) bytes -> str(string)로 변환

  b = s.encode('utf-8'

  ( s: bytes class, b: str class )

2) rstrip()을 사용하여 \n 제거

  b = b.rstrip()

4. 추가 설명

1) 'test string\n'.rstrip()

    'test string' 

    => \n 을 제거

2) 'test string \n \r\n\n\r \n\n'.rstrip()

    'test string'

    => whitespace(공백) 부터 오른쪽 모두 제거

3) 'test string \n \r\n\n\r \n\n'.rstrip('\n')

    'test string \n \r\n\n\r '

   => 단지 '\n'만 제거

4) >>> s = " \n\r\n \n abc def \n\r\n \n "

   >>> s.strip()

          'abc def'

   >>> s.lstrip()

          'abc def \n\r\n \n '

   >>> s.rstrip()

          ' \n\r\n \n abc def'

 

 

반응형