python

Python String.find() function

The python string find() function can be used to check whether a substring exists in a string or to get the index of a substring.

my_string = 'Tony Stark'

if (my_string.find('ta') != -1):
    print('Substring found')
else:
    print('Substring not found')

# -> Substring found

Using the above code, we are checking whether a substring exists in a string or not. We have defined a string my_string and we are using my_string.find('ta') to find the index of the substring ta. If the substring is found, the find() function will return the index of the substring. If not, it will return -1.

Python find() function definition

Python string find() function returns the first occurrence index of a substring.

If the substring or value could not be found in a string, it will return -1.

print( 'Orange'.find('h') )
# -> -1

Basic syntax

String.find(value, start_index, stop_index)

Parameters

Python string find() function takes one required parameter and two optional parameters.

value: This is a required parameter. This is the value of the substring that needs to be checked inside the string.

start_index: Optional parameter. Index value from where you want to start the search.

stop_index: Optional parameter. Index value where you want to stop the search.

my_str = "Hello World!"

index = my_str.find('o', 5, 9)
print(index)

# -> 7
We have a start index 5 and stop index 9 here. We are checking if a substring 'o' exists between 5 and 9 index values of a string.
Was this helpful?