Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python find() method

Python find() method

Python Strings Python Strings


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

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

"

;

print

str1

.

find

(

str2

)

;

print

str1

.

find

(

str2

,

10

)

;

print

str1

.

find

(

str2

,

40

)

;

The output of the above example is:


15
15
-1

Example (Python 2.0+)

info

=

'

abca

'

print

info

.

find

(

'

a

'

)

Starting at index 0, find the first occurrence of the substring in the string; the result is: 0

0

print

info

.

find

(

'

a

'

,

1

)

Starting at index 1, find the first occurrence of the substring in the string; the result is 3

3

print

info

.

find

(

'

3

'

)

Returns -1 if not found

1


Python Strings Python Strings