Python - How To Check Whether a String Contains Substring in Python

ID : 17

viewed : 171

Tags : PythonPython String

vote vote

99

It is quite often that we need to check whether the given string contains a specific substring. We will list some methods here, and then compare the running time performance to select the most efficient method.

We will take the string - It is a given string as the given string and given is the substring to be checked.

in Operator to Check Whether a String Contains a Substring

is the membership checking operator. x in y is evaluated to be True if x is a member of y, or in other words, y contains x.

It returns True if the string y contains the substring x.

>>> "given" in "It is a given string" True >>> "gaven" in "It is a given string" False 

in Operator Performance

import timeit  def in_method(given, sub):     return sub in given  print(min(timeit.repeat(lambda: in_method('It is a given string', 'given'))) 
0.2888628 

str.find() Method to Check Whether a String Contains Substring

find is a built-in method of string - .

It returns the lowest index in str where substring sub is found, otherwise returns -1 if sub is not found.

>>> givenStr = 'It is a given string' >>> givenStr.find('given') 8 >>> givenStr.find('gaven') -1 

str.find() Method Performance

import timeit  def find_method(given, sub):     return given.find(sub)  print(min(timeit.repeat(lambda: find_method('It is a given string', 'given')))) 
0.42845349999999993 

str.index() Method

str.index(sub) is a string built-in method that returns the lowest index in str where sub is found. It will raise ValueError when the substring sub is not found.

>>> givenStr = 'It is a given string' >>> givenStr.index('given') 8 >>> givenStr.index('gaven') Traceback (most recent call last):   File "<pyshell#7>", line 1, in <module>     givenStr.index('gaven') ValueError: substring not found 

str.index() Method Performance

import timeit  def find_method(given, sub):     return given.find(sub)  print(min(timeit.repeat(lambda: find_method('It is a given string', 'given')))) 
0.457951 

Substring Checking Solution Conclusion

  1. in operator is the one you should use to check whether a substring exists in the given string because it is the fastest
  2. str.find() and str.index() could also be used but not the optimal because of the poor performance

  • Related HOW TO?