Python – 测试子串顺序
给定两个字符串,检查子字符串字符是否以正确的顺序出现在字符串中。
Input : test_str = ‘geeksforgeeks’, K = ‘sees’
Output : True
Explanation : “s” after that “ee” and then “s” is present in order in string 1.
Input : test_str = ‘geeksforgeeks’, K = ‘seef’
Output : False
Explanation : Unordered String.
方法 #1:使用 join() + 生成器表达式 + in运算符
在此,我们检查我们使用 join() 连接子字符串中出现的所有字符,然后使用 in运算符检查子字符串是否存在。
Python3
# Python3 code to demonstrate working of
# Test substring order
# Using join() + in operator + generator expression
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing substring
K = 'seek'
# concatenating required characters
temp = lambda sub: ''.join(chr for chr in sub if chr in set(K))
# checking in order
res = K in temp(test_str)
# printing result
print("Is substring in order : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test substring order
# Using all() + next() + generator expression
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing substring
K = 'seek'
# concatenating required characters using next()
# all() used to test order
test_str = iter(test_str)
res = all(next((ele for ele in test_str if ele == chr), None) is not None for chr in K)
# printing result
print("Is substring in order : " + str(res))
输出
The original string is : geeksforgeeks
Is substring in order : True
方法 #2:使用 all() + next() + 生成器表达式
在此,我们使用 next() 和生成器表达式获取仅包含子字符串字符的字符串,为了检查顺序,对子字符串中的每个字符使用 all() 操作。
Python3
# Python3 code to demonstrate working of
# Test substring order
# Using all() + next() + generator expression
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing substring
K = 'seek'
# concatenating required characters using next()
# all() used to test order
test_str = iter(test_str)
res = all(next((ele for ele in test_str if ele == chr), None) is not None for chr in K)
# printing result
print("Is substring in order : " + str(res))
输出
The original string is : geeksforgeeks
Is substring in order : True