In Python, how to know whether a string contain a jump substring. like 'abcd' contain 'ad'

Question:

In Python, how to know whether a string contain a jump substring. like ‘abcd’ contain ‘ad’
‘I very like play basketball’ contain ‘like basketball’

Asked By: tianlin zhang

||

Answers:

You can create an iterator from the test string and validate that every character in the subsequence can be found in the sequence of characters generated by the iterator:

def is_subsequence(a, b):
    seq = iter(b)
    return all(i in seq for i in a)

so that:

print(is_subsequence('ad', 'abcd'))
print(is_subsequence('adc', 'abcd'))

outputs:

True
False

Demo: https://ideone.com/jGdpis

Answered By: blhsing
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.