Python String find method

Python provides the find() method to search in a given string. The Python string find method searches through the whole string, by default, to search for given characters or word and returns the index of the first occurrence.

The Python find method also allows to specify from where to start and end the search within the string.

An example of find method

Let us first look at its syntax which is followed by a few examples.

How to use the find() method

Following is the general syntax of using the find Python method:

String_to_search.find(string, start, end)

where

  • string_to_search is the string that you want to check if that string contains it or not?
  • The String in the brackets is the search term.
  • Start: It tells where should searching start in the given string.
  • End: specifies where should it end searching in the string.

Note that, If the string does not contain the search term, it will return -1.

Python String find method example

The following example checks whether the given string contains the search term by using the find() method.

See this example online

The output will be

37

What if the search term is not found?

The following example shows what happens if the search term is not found in the given string while using the Python find method. For that, a variable is given a value that does not exist in the search string. See what happens.

See this example online

The output:

-1

Check whether string contains: with start and end number

This example shows how you can use the start and end parameters to specify where to start and end the search.

See this example online

The output will be:

Tutorial starts at: 15

Tutorial is not found between 20 to 45 characters!

Tutorial is not found between 10 to 20 characters!

 

Useful reading – String Split method | Python replace method

Leave a Comment