ID : 17
viewed : 171
Tags : PythonPython String
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 Performanceimport 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 Substringfind
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 Performanceimport 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()
Methodstr.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 Performanceimport 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
in
operator is the one you should use to check whether a substring exists in the given string because it is the fasteststr.find()
and str.index()
could also be used but not the optimal because of the poor performance