Movatterモバイル変換


[0]ホーム

URL:


Open In App

This article will cover how to check if aPythonstring 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:

CheckPython Substring in Stringusing the If-Else

In Python, you can check python substring in string is present using an if-elsestatement. 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 usersMyString1="A geek in need is a geek indeed"if"need"inMyString1: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 usingIn Operator

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

Python
text="Geeks welcome to the Geek Kingdom!"if"Geek"intext:print("Substring found!")else:print("Substring not found!")if"For"intext: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 substrstring="geeks for geeks"# or string=input() -> taking input from the usersubstring="geeks"# or substring=input()# splitting words in a given strings=string.split()# checking condition# if substring is present in the given string then it gives output as yesifsubstringins: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 functionfind() 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
defcheck(string,sub_str):if(string.find(sub_str)==-1):print("NO")else:print("YES")# driver codestring="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 Pythoncount()method. If the substring is not found then "yes " will print otherwise "no will be printed".

Python
defcheck(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

TheIndex() methodreturns 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=0end=1000print(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 usinglist 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"ifs2inselse"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 usinglambda 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(lambdax:(s2ins),s.split()))print(["yes"ifxelse"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']foriina:ifi.__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 usesslicing 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
defis_substring(string,substring):foriinrange(len(string)-len(substring)+1):ifstring[i:i+len(substring)]==substring:returnTruereturnFalsestring="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 usingregular 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
importreMyString1="A geek in need is a geek indeed"ifre.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 stringimportoperatorasops="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) 


Improve
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp