
Python string find() - How to get the index of a substring in Python
The find()
returns the index of a substring.
s = 'book car desk'
x = s.find('book')
y = s.find('car')
z = s.find('desk')
print(x) # 0
print(y) # 5
print(z) # 9
There are 5 letters before car
in the string so the index of car
is 5. Similarly, there are no letter before book
in the string so its index is 0.
If there are multiple substrings
s = 'book car desk'
x = s.find('k')
print(x) # 3
That shows the method returns the first position of the substring. The k
appears twice (book and desk) but the find()
only returns the index of k in book
. The find()
returns the index of the first occurrence of a substring.
If not found
If the substring is not found, what does the find()
return?
s = 'book car desk'
x = s.find('apple')
print(x) # -1
The string doesn't contain apple
so the find()
returns -1. So you can check if the substring exists by using this method. But to check the substring existence, the simple if statement is simpler than the find()
.
s = 'book car desk'
if 'apple' in s:
print('contained')
else:
print('not contained')
# not contained
find() vs index() method
The find()
and index()
are similar and actually return the same index.
s = 'Facebook'
a = s.find('k')
b = s.index('k')
print(a) # 7
print(b) # 7
If the string doesn't contain the target substring, the find()
returns -1 but the index()
raises the ValueError exception. Facebook
doesn't have z
so the index()
raises the exception.
s = 'Facebook'
a = s.find('z')
b = s.index('z')
print(a) # -1
print(b) # ValueError: substring not found
Option parameters
The find()
can take three arguments at most; value (required), start (optional), end (optional). The first parameter "value" is a substring. The "start" is the position you want to search from. The "end" is the position you want to end searching.
s = 'Facebook'
'''
find(value, start, end)
'''
a = s.find('ce', 4, 7)
b = s.find('ce', 1, 5)
print(a) # -1
print(b) # 2
a
is -1 because 'Facebook'[4:7]
doesn't have ce
. Facebook
has ce
but 'Facebook'[4:7]
doesn't.
Comments
Powered by Markdown