Python3 find() Method
Description
The find() method checks whether the string contains a substring str. If the beg (start) and end (end) range are specified, it checks whether it is contained within the specified range. If the substring is found within the specified range, it returns the starting index of the substring in the string. If it is not found, it returns -1.
Syntax
Syntax of the find() method:
str.find(str, beg=0, end=len(string))
Parameters
- str -- The string to search for.
- beg -- Starting index, default is 0.
- end -- Ending index, default is the length of the string.
Return Value
Returns the starting index if the substring is found, otherwise returns -1.
Example
The following example demonstrates the find() method:
Example (Python 3.0+)
#!/usr/bin/python3
str1 = "Example example....wow!!!"
str2 = "exam";
print (str1.find(str2))
print (str1.find(str2, 5))
print (str1.find(str2, 10))
The output of the above example is:
7 7 -1
Example (Python 3.0+)
>>>info = 'abca'
>>> print(info.find('a')) # Start from index 0, find the first occurrence of the substring in the string, return result: 0
0
>>> print(info.find('a', 1)) # Start from index 1, find the first occurrence of the substring in the string, return result: 3
3
>>> print(info.find('3')) # Returns -1 if not found
-1
>>>
Other Extensions
Python3 Strings