Python3 find() Method
Description
The find() method checks whether a substring str is contained within a string. If the optional beg (start) and end (end) range is specified, it checks within that range. If the specified range includes the index value, it returns the starting index of the substring within the string. If the index value is not included, it returns -1.
Syntax
Syntax for the find() method:
str.find(str, beg=0, end=len(string))
Parameters
str-- The substring to search for.beg-- The starting index, default is 0.end-- The ending index, default is the length of the string.
Return Value
Returns the starting index if the substring is found, otherwise returns -1.
Examples
The following examples demonstrate the use of the find() method:
Example (Python 3.0+)
#!/usr/bin/python3
str1 = "Tutorial 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')) # Search from index 0 for the first occurrence of the substring in the string, return result: 0
0
>>>print(info.find('a', 1)) # Search from index 1 for the first occurrence of the substring: return result 3
3
>>>print(info.find('3')) # If not found, return -1
-1
>>>
YouTip