Search code examples
arrayspython-2.7search

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?


Solution

  • 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