Home > OS >  Python : stripping, converting bytes type
Python : stripping, converting bytes type

Time:01-29

Under Python 3.10, I do have an UDP socket that listens to a COM port. I do get datas like this :

b'SENDPKT: "STN1" "" "SH/DX\r"\x98\x00'

The infos SH/DX before the "\n" can change and has a different length and I need to extract them.

.strip('b\r') doesn't work.

Using .decode() and str(), I tried to convert this bytes datas to a string for easier manipulation, but that doesn't work either. I get an error "invalid start byte at position 27 for 0x98

Any guess, how I can solve this ?

Thanks,

CodePudding user response:

For sophisticated input you can try ignoring errors while decoding:

b = b'SENDPKT: "STN1" "" "SH/DX\r"\x98\x00'
s = b.decode(errors='ignore')
res = s[20:s.find('\r')]   # 'SH/DX'
  • Related