Home » Python

Python String | find() Method with Example

Python String | find() Method with Example, this method is an in-built method in Python and it is used to check whether a given substring is exists in the string or not.
Submitted by IncludeHelp, on July 19, 2018

String.find() Method

find() is an inbuilt method of python, it is used to check whether a sub-string exists in the string or not. If sub-string exists, the method returns the lowest index of the sub-string, if sub-string does not exist, method return -1.

Note: This method is case sensitive.

Syntax:

 String.find(sub_string[, start_index[, end_index]])

Parameters:

  • sub_string - a part of the string to be found in the string.
  • start_index - an optional parameter, it defines the starting index from where sub_string should be found.
  • end_index - an optional parameter, it defines end index of the string. Find method will find the sub_string till this end_index.

Return value:

  • Returns the lowest index of the sub_string, if it exits in the string.
  • Returns -1 if sub_string does not exist in the string.

Example:

# string in which we have to find the sub_string
str = "Hello world, how are you?"

# sub_string to find the given string 
sub_str = "how"

# find by sub_str
print (str.find (sub_str))

# find by sub_str with slice:start index
print (str.find (sub_str, 10))

# find by sub_str with slice:start index and slice: end index
print (str.find (sub_str, 10, 24))

# find a sub_str that does not exist
sub_str = "friend"
# find by sub_str
print (str.find (sub_str))

# find a sub_str with different case 
sub_str = "HOW"
# find by sub_str
print (str.find (sub_str))

Output

    13
    13
    13
    -1
    -1



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.