1

I am receiving a packet through a serial port but when I receive the packet it is of class bytes and looks like this:

b'>0011581158NNNNYNNN  +6\r'

How do I convert this to a normal string? When I try to take information from this string, it comes out as a decimal representation it appears.

WorldDominator
  • 141
  • 1
  • 5
  • 18
  • 2
    possible duplicate of [Convert byte array to Python string](http://stackoverflow.com/questions/606191/convert-byte-array-to-python-string) – aruisdante Jul 21 '14 at 18:48
  • @aruisdante alright that decode method didn't seem to work for me when I was working on a different part. However, do you know what the +6 part of my string stands for? I'm not very familiar with serial port communication. – WorldDominator Jul 21 '14 at 18:54
  • 2
    I mean, it's a byte array. It could be literally anything. The fact that it happens to work out to the characters ``'+6\r'`` could be a total coincidence. You need to know the packet format for whatever is sending you serial data. – aruisdante Jul 21 '14 at 19:09

1 Answers1

3

You can call decode on the bytes object to convert it to a string, but that only works if the bytes object actually represents text:

>>> bs = b'>0011581158NNNNYNNN  +6\r'
>>> bs.decode('utf-8')
'>0011581158NNNNYNNN  +6\r'

To really parse the input, you need to know the format, and what it actually means. To do that, identify the device that is connected to the serial port (A scanner? A robot? A receiver of some kind?). And look up the protocol. In your case, it may be a text-based protocol, but you'll often find that bytes stand for digits, in which you'll probably want to have a look at the struct module.

phihag
  • 278,196
  • 72
  • 453
  • 469