find() method of str class

The find() method of python str class finds and returns the lowest index of a specified substring in a given string;Start, Stop positions can be specified.

Str Updated 10 Mar 2017 1 min read

Method Name

find

Method Signature

find(sub[, start[, end]])

Method Overview

  • The find() method of str class, finds the position of substring in a given string.
  • find() returns the lowest index at which the substring is found.
  • The start position and end position at which the search for the substring should start can be specified using the start and end parameters.

Example

python
stringSample    = "pecan pie"

substr          = "pie"

pos             = stringSample.find(substr)

print("'{}' was found in '{}' at position:{}".format(substr, stringSample, pos))

stringSample    = "elvis presley"

substr          = "presley"

pos             = stringSample.find(substr)

print("'{}' was found in '{}' at position:{}".format(substr, stringSample, pos))

# find with start and stop specififed

stringSample    = "its now or never"

substr          = "or"

pos             = stringSample.find(substr,5,len(stringSample))

print("'{}' was found in '{}' at position:{}".format(substr, stringSample, pos))

Output

Output
'pie' was found in 'pecan pie' at position:6

'presley' was found in 'elvis presley' at position:6

'or' was found in 'its now or never' at position:8