How to consistently ignore one byte from a string

南楼画角 提交于 2019-12-11 07:57:12

问题


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?


回答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.




回答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).




回答3:


If you have a list in python, you can do

list = [x for x in originallist if x is not None]


来源:https://stackoverflow.com/questions/25480433/how-to-consistently-ignore-one-byte-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!