How To Consistently Ignore One Byte From A String
Solution 1:
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.
Solution 2:
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).
Solution 3:
If you have a list in python, you can do
list = [x for x in originallist if x is not None]
Post a Comment for "How To Consistently Ignore One Byte From A String"