Franck 38
Franck 38

Reputation: 5

Extract an int from a byte string

Since a switch from Python 2.7 to Python 3.7 I encounter a lot of issues with my old code:

I have:

>>> print(o)
b' Avail\n113782\n'
>>> print(type(o))
<class 'bytes'>

I would like to extract only the number 113782.

Upvotes: 0

Views: 629

Answers (1)

mkrieger1
mkrieger1

Reputation: 23235

Simply split it at the \n character:

>>> o.split(b'\n')
[b' Avail', b'113782', b'']

...and convert the second item to an integer:

>>> int(o.split(b'\n')[1])
113782

Make sure you also use a bytes object b'\n' for splitting, and not a string, '\n', to avoid this error:

>>> o.split('\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

Upvotes: 4

Related Questions