Check if String Contains Substring in Python - GeeksforGeeks (2024)

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:

  • Using the If-Else
  • Using In Operator
  • Checking using split() method
  • Using find() method
  • Using “count()” method
  • Using index() method
  • Using list comprehension
  • Using lambda function
  • Using __contains__”magic class.
  • Using Slicing Function
  • Using regular expressions
  • using operator contains() method

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 usersMyString1 = "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 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 yesif 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 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 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 = 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 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 Falsestring = "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 reMyString1 = "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 stringimport operator as ops="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.")


S

Striver

Check if String Contains Substring in Python - GeeksforGeeks (1)

Improve

Previous Article

How to Remove Letters From a String in Python

Next Article

Python - Words Frequency in String Shorthands

Please Login to comment...

Check if String Contains Substring in Python - GeeksforGeeks (2024)

FAQs

Check if String Contains Substring in Python - GeeksforGeeks? ›

Check Python Substring in String using Find() method

How to see if a string contains a substring in Python? ›

Using find() to check if a string contains another substring

We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.

How to check if a string contains a substring? ›

The includes() method

You can use JavaScript's includes() method to check whether a string contains a substring. This will return true if the substring is found, or false if not.

How do you check if a string contains a substring go? ›

Contains()

The method returns true if the substring is present, otherwise it returns false .

How do you check if a series contains substring in Python? ›

contains() is used to test if a pattern or substring is contained within a string of a Series or DataFrame. It is particularly useful for filtering rows based on text content. This method returns a Boolean Series showing whether each element in the Series or DataFrame contains the specified substring.

How do you check if a string does not contain a substring in Python? ›

The python str class has a __contains__() method that will check if a python string contains a substring. It will return true if it's found and will return false if it's not.

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

Python startswith() – The startswith() function determines whether a provided substring/prefix begins with a specific string. Python endswith() – The endswith() function determines whether a provided substring/suffix ends with a specific string.

How do you check if a cell contains a substring? ›

The Excel formula using IF, ISNUMBER, and SEARCH (or FIND) functions is a versatile method to detect partial text matches within cells. It allows you to check if a specific substring or character exists in a given cell and return custom outputs based on the presence or absence of the partial text.

How do you check if a string ends with a substring? ›

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

How to get a substring in Python? ›

Extract a substring from a string in Python
  1. substring = my_string[start:end] ...
  2. my_string = "Hello world!" substring = my_string[1:5] # will be "ello" substring = my_string[:5] # will be "Hello" substring = my_string[6:] # will be "world!"
Apr 15, 2023

How do you check if a string contains a substring from a list? ›

One approach to check if a string contains an element from a list is to convert the string and the list into sets and then check for the intersection between the sets. If the intersection is not an empty set, it means that the string contains an element from the list.

How do you identify a substring? ›

To find a substring in a string, we have a predefined function called substr() function in our C++ programming language. The substr() function takes 2 parameters pos and len as arguments to find and return the substring between the specified position and length.

How do you check if a list contains a string in Python? ›

Find String in List using count() method. The count() function is used to count the occurrence of a particular string in the list. If the count of a string is more than 0 in Python list of strings, it means that a particular string exists in the list, else that string doesn't exist in the list.

How do you check if a substring repeats in a string Python? ›

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!"

How do you check if a string array contains a substring? ›

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How to check if a string contains certain characters in Python? ›

Method 1: Check a string for a specific character using in keyword + loop. Traverse through the char array and for each character in arr check if that character is present in string s using an operator which returns a boolean value (either True or false).

How to extract a substring from a string in Python? ›

To get substrings in Python, we use slicing. A Python substring index marks where to start and end the slice. For example, in “Read”, 'R' is at index 0, 'e' at 1, and so on. It's crucial to note that in Python, the slicing operation uses start:stop indices.

Top Articles
Why Choose React For Web Development in 2024 - GeeksforGeeks
How to Deduct a Percentage in Excel
Devotion Showtimes Near Xscape Theatres Blankenbaker 16
Odawa Hypixel
Voorraad - Foodtrailers
Otterbrook Goldens
Poe Pohx Profile
P2P4U Net Soccer
Visustella Battle Core
Pollen Count Los Altos
Audrey Boustani Age
How Many Cc's Is A 96 Cubic Inch Engine
Colts seventh rotation of thin secondary raises concerns on roster evaluation
The Superhuman Guide to Twitter Advanced Search: 23 Hidden Ways to Use Advanced Search for Marketing and Sales
Apus.edu Login
Aucklanders brace for gales, hail, cold temperatures, possible blackouts; snow falls in Chch
Nine Perfect Strangers (Miniserie, 2021)
Royal Cuts Kentlands
Mccain Agportal
The Blind Showtimes Near Amc Merchants Crossing 16
Mail.zsthost Change Password
Rufus Benton "Bent" Moulds Jr. Obituary 2024 - Webb & Stephens Funeral Homes
What Channel Is Court Tv On Verizon Fios
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Touchless Car Wash Schaumburg
Craigslist Battle Ground Washington
Watch Your Lie in April English Sub/Dub online Free on HiAnime.to
Teekay Vop
2000 Ford F-150 for sale - Scottsdale, AZ - craigslist
Villano Antillano Desnuda
Star Wars Armada Wikia
Democrat And Chronicle Obituaries For This Week
Spirited Showtimes Near Marcus Twin Creek Cinema
Sony Wf-1000Xm4 Controls
Gncc Live Timing And Scoring
WOODSTOCK CELEBRATES 50 YEARS WITH COMPREHENSIVE 38-CD DELUXE BOXED SET | Rhino
Best New England Boarding Schools
EST to IST Converter - Time Zone Tool
Tamilyogi Ponniyin Selvan
Dying Light Nexus
Weather Underground Cedar Rapids
Vintage Stock Edmond Ok
Academic Calendar / Academics / Home
All Weapon Perks and Status Effects - Conan Exiles | Game...
Sara Carter Fox News Photos
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Bf273-11K-Cl
What Does the Death Card Mean in Tarot?
Diesel Technician/Mechanic III - Entry Level - transportation - job employment - craigslist
O.c Craigslist
Jasgotgass2
One Facing Life Maybe Crossword
Latest Posts
Article information

Author: Annamae Dooley

Last Updated:

Views: 5637

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.