Open In App

Python – Test substring order

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings, check if substring characters occur in correct order in string.

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.

Method #1 : Using join() + generator expression + in operator

In this, we check we join all the characters which occur in the substring using join(), post that check if substring is present using in operator.

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
 
 
def temp(sub): return ''.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))


Output

The original string is : geeksforgeeks
Is substring in order : True

Time Complexity: O(n)

Space Auxiliary: O(n)

Method #2 : Using all() + next() + generator expression

In this, we get the string with just substring characters using next() and generator expression, to check for order, all() operation is used for each character in substring.

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))


Output

The original string is : geeksforgeeks
Is substring in order : True

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #3 : Using find() method

Python3




# Python3 code to demonstrate working of
# Test substring order
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing substring
K = 'seek'
ns = ""
for i in test_str:
    if i in K:
        ns += i
res = False
if(ns.find(K) != -1):
    res = True
# printing result
print("Is substring in order : " + str(res))


Output

The original string is : geeksforgeeks
Is substring in order : True

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #4 : Using replace() and find() methods

Python3




# Python3 code to demonstrate working of
# Test substring order
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing substring
K = 'seek'
for i in test_str:
    if i not in K:
        test_str=test_str.replace(i,"")
res=False
if(test_str.find(K)!=-1):
    res=True
# printing result
print("Is substring in order : " + str(res))


Output

The original string is : geeksforgeeks
Is substring in order : True

Method #5 : Using operator.contains() method

Approach

  1. Replace all characters of test_str which are not present in K using replace() method
  2. Now check whether K is present in test_str using operator.contains() method
  3. Display the return value of operator.contains()

Python3




# Python3 code to demonstrate working of
# Test substring order
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing substring
K = 'seek'
for i in test_str:
    if i not in K:
        test_str=test_str.replace(i,"")
import operator
res=operator.contains(test_str,K)
# printing result
print("Is substring in order : " + str(res))


Output

The original string is : geeksforgeeks
Is substring in order : True

Time Complexity : O(N) N- length of string

Auxiliary Space – O(1) because res is a single variable

Method 6 :  using list comprehension and the all() function

Python3




# Python3 code to demonstrate working of
# Test substring order
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing substring
K = 'seek'
 
# using list comprehension and all()
res = all(K[i] in test_str[test_str.find(K[i-1])+1:] for i in range(1, len(K)))
 
# printing result
print("Is substring in order : " + str(res))


Output

The original string is : geeksforgeeks
Is substring in order : True

The time complexity of this approach is O(n^2), where n is the length of the substring K, because for each character in K, we need to search through the remaining part of test_str to find its position.

The auxiliary space complexity is O(1), because we only use a few extra variables to store the current position in test_str, the previous position found by find(), and the result of the all() function. No additional data structures are created.



Similar Reads

Python - Test if Substring occurs in specific position
Sometimes, while working with python strings, we can have a problem in which we need to test occurrence of substring. There is straight forward way to test this. But sometimes, we have a more specific problem in which we need to test if substring occurs at that particular position. Let's discuss certain ways in which this task can be performed. Met
6 min read
Python - Test Common Elements Order
Sometimes, while working with lists, we can have a problem in which we need to test if list contains common elements. This type of problem has been dealt many times and has lot of solutions. But sometimes, we might have a problem in which we need to check that those common elements appear in same order in both list or not. Let's discuss certain way
4 min read
Python Program to test whether the length of rows are in increasing order
Given a Matrix, the following program is used to test if length all rows of a matrix are in increasing order or not. If yes, it returns True, otherwise False. Input : test_list = [[3], [1, 7], [10, 2, 4], [8, 6, 5, 1, 4]] Output : True Explanation : 1 < 2 < 3 < 5, increasing lengths of rows, hence True.Input : test_list = [[3], [1, 7], [10
4 min read
Substring Matching of Test Names in Pytest
A free and open-source Python framework that is used to execute and test codes is known as Pytest. Suppose you have written all the test cases related to code on on test file, but you don't want to execute all test cases at once for testing the code. Then, you can do so, by adding some unique portion of names to test cases that you want to run toge
2 min read
Stop Test Suite after N Test Failures in Pytest
The Python package which makes applications easy to write small, readable tests, and can scale to support complex functional testing is known as Pytest. The Pytest can have various checks, which keep running until it encounters the first failure or error. But if the user wants the test suite to run until it encounters N failures, he can use the max
2 min read
Kolmogorov-Smirnov Test (KS Test)
The Kolmogorov-Smirnov (KS) test is a non-parametric method for comparing distributions, essential for various applications in diverse fields. In this article, we will look at the non-parametric test which can be used to determine whether the shape of the two distributions is the same or not. What is Kolmogorov-Smirnov Test?Kolmogorov–Smirnov Test
13 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
SequenceMatcher in Python for Longest Common Substring
Given two strings ‘X’ and ‘Y’, print the longest common sub-string. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx" Output : abcdez We have existing solution for this problem please refer Print the longest common substring link. We will solve problem in python using SequenceMatcher.find
2 min read
Python | Find longest consecutive letter and digit substring
Given a String (may contain both letters and digits), write a Python program to find the longest consecutive letter and digit substring. Examples: Input : geeks123available Output : ('available', 123) Input : 98apple658pine Output : ('apple', 658) Approach #1 : Brute force This is the Naive or brute force approach to find the longest consecutive le
5 min read
Python | Check if substring present in string
Let us solve this general problem of finding if a particular piece of string is present in a larger string in different ways. This is a very common kind of problem every programmer comes across atleast once in his/her lifetime. This article gives various techniques to solve it. Method 1: Using in operator The in operator is the most generic, fastes
5 min read
Practice Tags :
three90RightbarBannerImg