Python find() method
Description
The Python find() method checks whether a string contains the substring str. If the beg (start) and end ranges are specified, it checks within that range. It returns the starting index if the substring is found, otherwise -1.
Syntax
Syntax of the find() method:
str.find(str, beg=0, end=len(string))
Parameters
- str -- the string to search for
- beg -- the starting index, defaults to 0.
- end -- the ending index, defaults to the length of the string.
Return Value
Returns the starting index if the substring is contained, otherwise -1.
Example
The following example demonstrates the find() method:
Example (Python 2.0+)
#!/usr/bin/python
str1
=
"
this is string example....wow!!!
"
;
str2
=
"
exam
"
;
str1
.
find
(
str2
)
;
str1
.
find
(
str2
,
10
)
;
str1
.
find
(
str2
,
40
)
;
The output of the above example is:
15
15
-1
Example (Python 2.0+)
info
=
'
abca
'
info
.
find
(
'
a
'
)
Starting at index 0, find the first occurrence of the substring in the string; the result is: 0
0
info
.
find
(
'
a
'
,
1
)
Starting at index 1, find the first occurrence of the substring in the string; the result is 3
3
info
.
find
(
'
3
'
)
Returns -1 if not found
1
Python Strings