python bytes array display is different to element value

Question:

I have a bytes array returned from a hardware module,
the len is:

len(a)
51

when I display it in vscode or terminal, it shows:

b’>128 143 134 135 141 139 134 120 137 135 132 143 rn’

when I try to convert it to list:

     s = list(a.strip())
s[0]
62
s[1]
49
s[2]
50
s[3]
56

how could I convert list s to 12 integers shown in vscode or terminal?

Asked By: adameye2020

||

Answers:

That’s a bytes string. You could use strip to get rid of the rn on the end, then slice 1: to get rid of the > at the front. Then, split on spaces to get a list of strings and convert those to integers.

test = b'>128 143 134 135 141 139 134 120 137 135 132 143 rn'
l = [int(val) for val in a.strip()[1:].split(b" ")]
print(l)

output

[128, 143, 134, 135, 141, 139, 134, 120, 137, 135, 132, 143]
Answered By: tdelaney

I went for a regex that looks for number-like things:

import re

b = b'>128 143 134 135 141 139 134 120 137 135 132 143 rn'

l = [int(x) for x in re.findall(r'[0-9]+', str(b))]
Answered By: Mark Setchell
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.