hyde
hyde

Reputation: 62787

How to test if a sequence starts with values in another sequence?

How to simply test, if a sequence starts with certain values in Python3?

There's of course the solution of writing a custom function, example below. But does Python itself offer some solution? Something more pythonic, an understandable one-liner would be good.


def startswith(sequence, prefix):
    """return true if sequence starts with items in prefix"""
    if len(prefix) > len(sequence):
        return False
    for i in range(len(prefix)):
        if sequence[i] != prefix[i]:
            return False
    return True

Upvotes: 1

Views: 143

Answers (1)

John La Rooy
John La Rooy

Reputation: 304137

len(prefix) <= len(sequence) and all(i==j for i, j in zip(prefix, sequence))

Upvotes: 4

Related Questions