Reputation: 13206
I am dealing with a program that consistently returns many byte
objects.
Frequently it returns the null b'00'
in the middle of strings. I want to completely ignore that, (say if I were to make an array of these bytes). Is the only way to include a:
if bytes != b'\x00':
# Do something
in every single loop / part of my code or is there a better way for me to skip those bytes?
Bonus Question: When referring to situations such as this in Python 3, is a long "string" of bytes a "byte object", "string of bytes" or "byte array"?
What is the proper terminology?
Upvotes: 1
Views: 1484
Reputation: 3550
If you have a list in python, you can do
list = [x for x in originallist if x is not None]
Upvotes: 0
Reputation: 17176
Usually you'd use a filtered version of the object, for example:
In [63]: test
Out[63]: 'hello\x00world'
In [68]: for my_bytes in filter(lambda x: x != b'\x00', test):
....: print(my_bytes)
....:
h
e
l
l
o
w
o
r
l
d
Note I used my_bytes
instead of bytes
, which is a built-in name you'd rather not overwrite.
Similar you can also simply construct a filtered bytes object for further processing:
In [62]: test = b'hello\x00world'
In [63]: test
Out[63]: 'hello\x00world'
In [64]: test_without_nulls = bytes(filter(lambda x: x != b'\x00', test))
In [65]: test_without_nulls
Out[65]: 'helloworld'
I usually use bytes
objects as it does not share the interface with strings in python 3. Certainly not byte arrays.
Upvotes: 3
Reputation: 1121266
You can use a membership test using in
:
>>> b'\x00' in bytes([1, 2, 3])
False
>>> b'\x00' in bytes([0, 1, 2, 3])
True
Here b'\x00'
produces a bytes
object with a single NULL byte (as opposed to b'00'
which produces an object of length 2 with two bytes with integer values 48).
I call these things bytes
objects, sometimes byte strings, but the latter usually in context of Python 2 only. A bytearray
is a separate, distinct type (a mutable version of the bytes
type).
Upvotes: 1