Searches the string for a given substring
Usage
The find()
method searches for the first occurrence of the specified substring sub and returns its index. If specified substring is not found, it returns -1.
The optional arguments start and end are used to limit the search to a particular portion of the string.
The find()
method should be used only if you need to know the position of sub.
To check if sub is a substring or not, use the in
operator:
>>> 'Py' in 'Python'
True
Syntax
string.find(sub,start,end)
Parameter | Condition | Description |
sub | Required | Any string you want to search for |
start | Optional | An index specifying where to start the search. Default is 0. |
end | Optional | An index specifying where to stop the search. Default is the end of the string. |
Basic Examples
# Find if substring 'Developer' contains in a string
S = 'Bob is a Developer at ABC'
x = S.find('Developer')
print(x)
# Prints 9
find()
method returns -1 if specified substring is not found in the string.
# Find if substring 'Manager' contains in a string
S = 'Bob is a Developer at ABC'
x = S.find('Manager')
print(x)
# Prints -1
Limit the find() Search
If you want to search the string from the middle, specify the start parameter.
# Find 'Big' starting a position 7
S = 'Big, Bigger, Biggest'
x = S.find('Big',7)
print(x)
# Prints 13
You can also specify where to stop the search with end parameter.
# Find 'Big' in between 2 & 10
S = 'Big, Bigger, Biggest'
x = S.find('Big',2,10)
print(x)
# Prints 5
find() vs index()
The find()
method is identical to the index() method.
The only difference is that the index()
method raises a ValueError exception, if the substring is not found.
S = 'Bob is a Developer at ABC'
x = S.find('Manager')
print(x)
# Prints -1
S = 'Bob is a Developer at ABC'
x = S.index('Manager')
# Triggers ValueError: substring not found