Check String is Subsequence in Python

  • Post category:String

A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence “ace” is a subsequence of “abcde” because you can delete the “b” and “d” to get “ace”. To check if a string is a subsequence of another string, you can use the following code.

Step 1: Create two strings

str1 = "CodeAllow"
str2 = "CodAl"

print("str1 = ", str1)
print("str1 type = ", type(str1))

print("str2 = ", str2)
print("str2 type = ", type(str2))

Step 2: check if string is subsequence

i = 0
j = 0

while i < len(str1) and j < len(str2):
    if str1[i] == str2[j]:
        j += 1
    i += 1

if j == len(str2):

    print("Not Subsequence")
str1 =  CodeAllow
str1 type =  <class 'str'>
str2 =  CodAl
str2 type =  <class 'str'>

Free resources to learn advanced skills: AiHints and CodeAllow