Finding subsequence (nonconsecutive)

Using an iterator trick:

it = iter(haystack)
all(x in it for x in needle)

This is only a concise version of the same idea presented in another answer.


I don't know if there's builtin function, but it is rather simple to do manually

def exists(a, b):
    """checks if b exists in a as a subsequence"""
    pos = 0
    for ch in a:
        if pos < len(b) and ch == b[pos]:
            pos += 1
    return pos == len(b)
>>> exists("moo", "mo")
True
>>> exists("moo", "oo")
True
>>> exists("moo", "ooo")
False
>>> exists("haystack", "hack")
True
>>> exists("haystack", "hach")
False
>>>

Tags:

Python

String