user857990
user857990

Reputation: 1220

Search for sequence of bytes in python

I receive an array like the following:

array('b', [71, 69, 84, 32, 47, 97, 115, 115, 101])

and I would like to know if a certain sequence of bytes appears in it, e.g. 47 98 113

What is the quickest and most pythonic way to do so?

Upvotes: 0

Views: 726

Answers (2)

Sugarsail1
Sugarsail1

Reputation: 11

If a is the stream of bytes, and b is the sequence of bytes which you are looking for, the following instruction:

a.find(b)

returns:

  • -1 if it's not in there
  • otherwise it will return the index number where the beginning of b is found in a

Upvotes: 1

zipa
zipa

Reputation: 27879

Convert it first to a list with .tolist(), and then if you want to search for exact sequence this could be helpful:

a = [71, 69, 84, 32, 47, 97, 115, 115, 101]
b = [47, 98, 113]
def search(what, where):
    if len(what) > len(where):
        return False
    idx = [i for i, x in enumerate(where) if what[0] == x]
    for item in idx:
        if where[item:item+len(what)] == what:
            return True
    return False
search(b,a)
#False       

Upvotes: 1

Related Questions