Find() Method Of Str Class

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:

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:

'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

 


Copyright 2019 © pythontic.com