Method 1: Using the in
operator
in
operators is the most versatile, quickest way to check substrings, cardinality in
operators in python are very well known and are used in many operations throughout the language.
# Python 3 demo code # check a substring in a string # use in a statement # initialization string test_str = "GeeksforGeeks" # use for checking # for substring print ( "Does for exists in GeeksforGeeks? : " ) if " for " in test_str: print ( "Yes, String found" ) else : print ( "No, String not found " ) |
Output:
Does for exists in GeeksforGeeks?: Yes, String found
Method 2: Using str.find ()
The str.find () method is usually used to get the smallest index at which a string occurs, but also returns -1 if the row is missing, therefore, if any value returns" = 0, line present, otherwise missing.
# Python 3 demo code # checking a substring in a string # using str.find () # initialization string test_str = "GeeksforGeeks" # using str.find () to check # for substring res = test_str.find ( "for" ) if res" = 0 : print ( " for is present in Python.Engineering " ) else : print ( " for is not present in Python.Engineering " ) |
Output:
for is present in Python.Engineering
Method 3: use str.index()
This method can be used to perform a similar task, but like str.find (), it does not return a value, but a ValueError if the string is missing , so catching an exception is the way to test a string in a substring.
# Python 3 demo code # checking a substring in a string # using str.index () # initialization string test_str = "GeeksforGeeks" # using str.index () to check # for substring try : res = test_str .index ( "forg" ) print ( " forg exists in Python.Engineering " ) except : print ( "forg does not exists in GeeksforGeeks" ) |
Output:
forg does not exists in Python.Engineering
Method 4: Use operator.contains ()
This is a lesser known method for checking a substring in a string, this method is also effective for this task of checking a string in a string.
# Python 3 demo code # check and substrings in the string # using operator.contains () import operator # initializing string test_str = "GeeksforGeeks" # using operator.contains () to check # for substring if operator.contains (test_str, "for" ): print ( "for is present in GeeksforGeeks" ) else : print ( "for is not present in GeeksforGeeks" ) |
tbody >
Output:
for is present in Python.Engineering
Python | Check if substring is present in string Python functions: Questions
Python | Check if substring is present in string String Variables: Questions