The Wayback Machine - https://web.archive.org/web/20240910190952/https://www.geeksforgeeks.org/check-if-string-contains-substring-in-python/
Open In App

Check if String Contains Substring in Python

Last Updated : 20 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
36.62%
55.8K

This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. 

Input: Substring = "geeks" 
String="geeks for geeks"
Output: yes
Input: Substring = "geek"
String="geeks for geeks"
Output: yes
Explanation: In this, we are checking if the substring is present in a given string or not.

Python Substring in String

Checking a substring is one of the most used tasks in Python. Python uses many methods to check a string containing a substring like, find(), index(), count(), etc. The most efficient and fast method is by using an “in” operator which is used as a comparison operator. Here we will cover different approaches:

Check Python Substring in String using the If-Else

In Python, you can check python substring in string is present using an if-else statement. The if-else statement allows you to conditionally execute different blocks of code based on whether the condition is true or false.

Python
# Take input from users
MyString1 = "A geek in need is a geek indeed"

if "need" in MyString1:
    print("Yes! it is present in the string")
else:
    print("No! it is not present")

Output

Yes! it is present in the string

Time Complexity : O(n)
Auxiliary Space : O(1)

Checking Python Substring in String using In Operator

In Python, you can easily check if a substring is present in a given string using the in operator. The in operator is used to test whether a particular value (substring) exists within a sequence.

Python
text = "Geeks welcome to the Geek Kingdom!"

if "Geek" in text:
    print("Substring found!")
else:
    print("Substring not found!")

if "For" in text:
    print("Substring found!")
else:
    print("Substring not found!")

Output

Substring found!
Substring not found!

Time Complexity : O(n)
Auxiliary Space : O(1)

Checking Python Substring in String using Split() method

Checking python substring in string is present or not using split(). First split the given string into words and store them in a variable s then using the if condition, check if a substring is present in the given string or not.

Python
# input strings str1 and substr
string = "geeks for geeks"  # or string=input() -> taking input from the user
substring = "geeks"  # or substring=input()

# splitting words in a given string
s = string.split()

# checking condition
# if substring is present in the given string then it gives output as yes
if substring in s:
    print("yes")
else:
    print("no")

Output

Yes

Time Complexity : O(n + m)
Auxiliary Space : O(n)

Check Python Substring in String using Find() method

We can iteratively check for every word, but Python provides us an inbuilt function find() which checks if a substring is present in the string, which is done in one line. find() function returns -1 if it is not found, else it returns the first occurrence, so using this function this problem can be solved. 

Python
def check(string, sub_str):
    if (string.find(sub_str) == -1):
        print("NO")
    else:
        print("YES")


# driver code
string = "geeks for geeks"
sub_str = "geek"
check(string, sub_str)

Output

Yes

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in String using Count() Method

You can also count the number of occurrences of a specific substring in a string, then you can use the Python count() method. If the substring is not found then “yes ” will print otherwise “no will be printed”.

Python
def check(s2, s1):
    if (s2.count(s1) > 0):
        print("YES")
    else:
        print("NO")


s2 = "A geek in need is a geek indeed"
s1 = "geeks"
check(s2, s1)

Output

No

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in string using Index() method

The Index() method returns the starting index of the substring passed as a parameter. Here “substring” is present at index 16.

Python
any_string = "Geeks for Geeks substring "
start = 0
end = 1000
print(any_string.index('substring', start, end))

Output

16

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in String using List Comprehension 

To check Python substring in string using list comprehension. Using list comprehension provides a concise way to check for a substring in a string and determine if it exists in any of the words.

Python
s="geeks for geeks" 
s2="geeks" 
print(["yes" if s2 in s else "no"])

Output

['Yes']

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in String using Lambda Function

To check Python substring in string using lambda function. Using a lambda function provides a concise way to check for a substring in a string and determine if it exists in any of the words.

Python
s="geeks for geeks" 
s2="geeks" 
x=list(filter(lambda x: (s2 in s),s.split())) 
print(["yes" if x else "no"])

Output

['Yes']

Time Complexity : O(n + m)
Auxiliary Space : O(m)

Check Python Substring in String using the “__contains__” magic class.

To check python substring in string we use __contains__(). This method is used to check if the string is present in the other string or not. 

Python
a = ['Geeks-13', 'for-56', 'Geeks-78', 'xyz-46']
for i in a:
    if i.__contains__("Geeks"):
        print(f"Yes! {i} is containing.")

Output

Yes! Geeks-13 is containing.
Yes! Geeks-78 is containing.

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in String using Slicing 

Check python substring in string using slicing. This implementation uses a loop to iterate through every possible starting index of the substring in the string, and then uses slicing to compare the current substring to the substring argument. If the current substring matches the substring argument, then the function returns True otherwise returns False.

Python
def is_substring(string, substring):
    for i in range(len(string) - len(substring) + 1):
        if string[i:i+len(substring)] == substring:
            return True
    return False
string = "A geeks in need is a geek indeed"
substring = "geeks"
print(is_substring(string,substring))

Output

True

Time Complexity : O(n*m) 
where n is the length of the string argument and m is the length of the substring argument. This is because the function uses a loop to iterate through every possible starting index of the substring in the string and then uses slicing to compare the current substring to the substring argument. In the worst case, the loop will iterate n-m+1 times, and each slice operation takes O(m) time, resulting in a total time complexity of O((n-m+1)m) = O(nm).
Auxiliary Space : O(1) 

Check Python Substring in String using Regular Expression

In Python, you can check python substring in string is present using regular expressions. Regular expressions provide powerful pattern matching capabilities, allowing you to define complex search patterns for substring matching. Here’s how you can use regular expressions to check for a substring in a string.

Python
import re

MyString1 = "A geek in need is a geek indeed"

if re.search("need", MyString1):
    print("Yes! it is present in the string")
else:
    print("No! it is not present")

Output

Yes! it is present in the string

Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(1), as we are not using any additional space

Check Python Substring in String using operator.contains() method

This Approach Used operator.contains() method to check whether the substring is present in string If the condition is True print yes otherwise print no

Python
#Python program to check if a substring is present in a given string
import operator as op
s="geeks for geeks"
s2="geeks"
if(op.contains(s,s2)):
    print("yes")
else:
    print("no")

Output

Yes

Time Complexity : O(N)
Auxiliary Space : O(1) 


Check if String Contains Substring in Python – FAQs

How to check if a string contains an exact substring in Python?

To check if a string contains an exact substring, you can use the in keyword:

main_string = "Hello, world!"
substring = "world"
# Check if substring is in main_string
if substring in main_string:
print("Substring found!")
else:
print("Substring not found.")

How to check if a string contains a list of substrings?

To check if a string contains any of a list of substrings, you can use a loop or a generator expression with the any function:

main_string = "Hello, world!"
substrings = ["world", "Python", "Hello"]
# Check if any of the substrings are in main_string
if any(sub in main_string for sub in substrings):
print("At least one substring found!")
else:
print("No substrings found.")

How to check if a string starts with a substring in Python?

To check if a string starts with a particular substring, you can use the startswith() method:

main_string = "Hello, world!"
substring = "Hello"
# Check if main_string starts with substring
if main_string.startswith(substring):
print("String starts with the substring.")
else:
print("String does not start with the substring.")

How to check if a string ends with a substring in Python?

To check if a string ends with a particular substring, you can use the endswith() method:

main_string = "Hello, world!"
substring = "world!"
# Check if main_string ends with substring
if main_string.endswith(substring):
print("String ends with the substring.")
else:
print("String does not end with the substring.")

How to check if a substring repeats in a string in Python?

To check if a substring repeats in a string, you can use the count() method to see if the substring appears more than once:

main_string = "Hello, world! Hello again!"
substring = "Hello"
# Check if substring repeats in main_string
if main_string.count(substring) > 1:
print("Substring repeats in the string.")
else:
print("Substring does not repeat in the string.")


Previous Article
Next Article

Similar Reads

Check if a string contains an anagram of another string as its substring
Given two strings S1 and S2, the task is to check if S2 contains an anagram of S1 as its substring. Examples: Input: S1 = "ab", S2 = "bbpobac"Output: YesExplanation: String S2 contains anagram "ba" of S1 ("ba"). Input: S1 = "ab", S2 = "cbddaoo"Output: No Approach: Follow the steps below to solve the problem: Initialize two Hashmaps s1hash and s2has
7 min read
Length of smallest substring of a given string which contains another string as subsequence | Set 2
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. Examples: Input: A = "abcdefababaef", B = "abf"Output: 5Explanation:Smallest substring of A having B as subsequence is abcdef.Therefore, the required length is 5. Input: A = "abcdefababaef", B = "aef"Output: 3 Recommended: Please solve it on "PRACT
12 min read
Find length of smallest substring of a given string which contains another string as subsequence
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. If there are multiple such substrings in A, return the substring that has the smallest starting index. Examples : Input : A = "abcedbaced" B = "bed"Output : "bced"Explanation : The substring A[2 : 5] is the shortest substring that contains the stri
15 min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B is a substring of A. Input: S = "abcd"Output: No
5 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Check if given number contains only “01” and “10” as substring in its binary representation
Given a number N, the task is to check if the binary representation of the number N has only "01" and "10" as a substring or not. If found to be true, then print "Yes". Otherwise, print "No".Examples: Input: N = 5 Output: Yes Explanation: (5)10 is (101)2 which contains only "01" and "10" as substring.Input: N = 11 Output: No Explanation: (11)10 is
6 min read
Minimum flips required in a binary string such that all K-size substring contains 1
Given a binary string str of size N and a positive integer K, the task is to find the minimum number of flips required to make all substring of size K contain at least one '1'.Examples: Input: str = "0001", K = 2 Output: 1 Explanation: Flipping the bit at index 1 modifies str to "0101". All substrings of size 2 are "01", "10", and "01". Each substr
11 min read
Count ways to partition a Binary String such that each substring contains exactly two 0s
Given binary string str, the task is to find the count of ways to partition the string such that each partitioned substring contains exactly two 0s. Examples: Input: str = "00100" Output: 2Explanation: Possible ways to partition the string such that each partition contains exactly two 0s are: { {"00", "100"}, {"001", "00"} }. Therefore, the require
6 min read
Find least start index of a substring from given String that contains all the given words in a contiguous manner
Given a string S and an array of equal length words (strings) arr[]. The task is to find the minimum start index of the substring that contains all the given words in a contiguous manner. If no such index is found, return -1.Note: The words can be in any sequence. Examples: Input: arr[ ] = {"bat", "bal", "cat"}, S = "hellocatbyebalbatcatyo"Output:
9 min read
Check if substring S1 appear after any occurrence of substring S2 in given sentence
Given strings S1, S2 and S, the task is to check if every substring of S which is same as S1 has another substring of S same as S2 before it. It is given that S1 is always present as a substring in the string S. Examples: Input: S1 = "code", S2 = "geek", S = "sxygeeksgcodetecode"Output: TrueExplanation: Substring S2 is present before both the occur
4 min read
Python SQLAlchemy - Write a query where a column contains a substring
In this article, we discussed how to extract the column values containing substring in SQLAlchemy against a PostgreSQL database in python. In SQLAlchemy, generic functions like SUM, MIN, MAX, are invoked like conventional SQL functions using the func attribute. Some common functions used in SQLAlchemy are contains, count, cube, current_date, curren
2 min read
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'nd substring. Examples: Input : "11235813" Output : ["1", "1", "2", "3", "5", "8", "13"] Input : "1111223" Output : ["1", "11", "12", "23"] Input : "1111213" Output : ["11", "1", "12", "13"] Input : "11121114" Output : []Iterate through the given string by pickin
9 min read
Count occurrences of substring X before every occurrence of substring Y in a given string
Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = ”abcdefdefabc”, X = ”def”, Y = ”abc”Output: 0 2Explanation:First occurrence of Y(= "abc"): No of occurrences of X(=
6 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s. Examples: Input: str = "00101101"Output: 2Explanation: Removing str[2] and str[6] or removing str[3] and str[6] modifies the given binary string to
11 min read
Find if a given string can be represented from a substring by iterating the substring “n” times
Given a string 'str', check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Examples: Input: str = "abcabcabc" Output: true The given string is 3 times repetition of "abc" Input: str = "abadabad" Output: true The given string is 2 times repetition of "abad" Input: str = "aabaabaabaab" Ou
15+ min read
Check if a string contains a palindromic sub-string of even length
S is string containing only lowercase English alphabets. We need to find if there exists at least one palindromic sub-string whose length is even. Examples: Input : aassssOutput : YESInput : gfgOutput : NOApproach: Approach to solve this problem is to check all even-length substrings of the given string and check if any of them is a palindrome. Thi
8 min read
Minimum K such that every substring of length atleast K contains a character c
Given a string S containing lowercase latin letters. A character c is called K-amazing if every substring of S with length atleast K contains this character c. Find the minimum possible K such that there exists atleast one K-amazing character. Examples: Input : S = "abcde" Output :3 Explanation : Every substring of length atleast 3 contains charact
11 min read
Length of the smallest substring which contains all vowels
Given string str consisting of only lowercase English alphabets, the task is to find the substring of the smallest length which contains all the vowels. If no such substring is found, print -1. Example: Input: str = "babeivoucu" Output: 7 Explanation: Smallest substring which contains each vowel atleast once is "abeivou" of length 7. Input: str = "
15+ min read
Length of the longest substring that contains even number of vowels
Given a string S consisting of N lowercase characters, the task is to find the length of the longest substring consisting of each vowel an even number of times Examples: Input: S= "bcbcbc"Output: 6Explanation:Consider the substring S[0, 5] i.e., "bcbcbc" is the longest substring because all vowels: a, e, i, o and u appear 0(which is even) number of
8 min read
Minimum K such that every substring of length at least K contains a character c | Set-2
Given a string S consisting of N lowercase English alphabets, and also given that a character C is called K-amazing, if every substring of length at least K contains this character C, the task is to find the minimum possible K such that there exists at least one K-amazing character. Examples: Input: S = “abcde” Output: 3 Explanation: Every, substri
8 min read
Convert s1 into a Palindrome such that s1 contains s2 as Substring
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contains s2 as a substring in a minimum number of operations. In a single operation, we can replace any word of s1 with any character. If it is not possible to convert s1 such that it is a palindrome as well as contains a substring of s2, then return -1. Examples:
9 min read
Python program to check if a string contains all unique characters
To implement an algorithm to determine if a string contains all unique characters. Examples: Input : s = "abcd" Output: True "abcd" doesn't contain any duplicates. Hence the output is True. Input : s = "abbd" Output: False "abbd" contains duplicates. Hence the output is False. One solution is to create an array of boolean values, where the flag at
3 min read
Queries to check if string B exists as substring in string A
Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) - 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A). Examples: Input: A = "abababa", B = "aba", q[] = {0, 1
15+ min read
Check if the given string is shuffled substring of another string
Given strings str1 and str2. The task is to find if str1 is a substring in the shuffled form of str2 or not. Print "YES" if str1 is a substring in shuffled form of str2 else print "NO". Example Input: str1 = "onetwofour", str2 = "hellofourtwooneworld" Output: YES Explanation: str1 is substring in shuffled form of str2 as str2 = "hello" + "fourtwoon
15 min read
Check if a string can be converted to another given string by removal of a substring
Given two strings S and T of length N and M respectively, the task is to check if the string S can be converted to the string T by removing at most one substring of the string S. If found to be true, then print “YES”. Otherwise, print “NO”. Example: Input: S = “abcdef”, T = “abc” Output: YES Explanation: Removing the substring { S[3], â€Ķ, S[5] } mod
7 min read
Check if given string is a substring of string formed by repeated concatenation of z to a
Given a string str, the task is to check if string str is a substring of an infinite length string S in which lowercase alphabets are concatenated in reverse order as: S = "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba...." Examples: Input: str = "cbaz"Output: YES Explanation:Given string "cbaz" is a valid sub string of S. Input: str = "ywxt
10 min read
Length of the largest substring which have character with frequency greater than or equal to half of the substring
Given a string S consisting of characters from 'a' to 'z'. The task is to find the length of the largest substring of S which contains a character whose frequency in the sub-string is greater than or equal to half of the length of the substring.Note: For odd-length substring, to calculate half-length consider integer division. For example, half of
10 min read
Minimum length of substring whose rotation generates a palindromic substring
Given a string str, the task is to find the minimum length of substring required to rotate that generates a palindromic substring from the given string. Examples: Input: str = "abcbd" Output: 0 Explanation: No palindromic substring can be generated. There is no repeated character in the string. Input: str = "abcdeba" Output: 3 Explanation: Rotate s
7 min read
Minimize replacement of bits to make the count of 01 substring equal to 10 substring
Given a binary string str. The task is to minimize the number of replacements of '0' by '1' or '1' by '0' to balance the binary string. A binary string is said to be balanced: "if the number of "01" substring = number of "10" substring". Examples: Input: str = "101010" Output: 1Explanation: "01" = 2 & "10" = 3. So change the last character to '
4 min read
Practice Tags :