AppDividend
Latest Code Tutorials

Python String Find Example | Find() Method Tutorial

0

Python String Find Example | Find() Method Tutorial is today’s topic. The find() method returns the index of the first occurrence of the substring (if found). If not found, it returns -1. Python String find() method is used to find the index of a substring in the string. If the start and end indexes are not provided then by default, it takes 0 and length -1 as starting and ending indexes where the ending indexes are not included in our search.

Python String Find Example

String find() method is almost the same as the String index() method, and the only difference is that the index() method raises an exception if the value is not found.

The syntax for the find() method is following.

string.find(value, start, end)

The value parameter is required, and it is the value we are searching for.

The start parameter is optional, and it is where to start searching for.

The end parameter is optional, and it is where to end the search.

The find() method returns an integer value.  If substring exists inside the string, it returns the index of the first occurrence of the substring. If substring doesn’t exist inside the string, it returns -1.

Let’s see the following example.

# app.py

line = 'Every Marvel Movies are great movies'
index = line.find('Marvel')
print(index)

Here, the string index starts from 0. So the Marvel substring is starting from 6th. So the output is 6th.

 

Python String Find Example | Find() Method Tutorial

Find Letter between positions

Let’s find the first letter occurrence between the specified positions.

# app.py

line = 'Every Marvel Movies are great movies'
index = line.find('e', 6, 20)
print(index)

In the above example, we will start searching for letter from position and ending at 20. The output is following.

 

Find Letter between positions

Let’s see another example where we don’t find the character in the String.

# app.py

line = 'Every Marvel Movies are great movies'
index = line.find('k')
print(index)

The above example will return the -1 as we do not find any character in the string.

 

Python Find() Method Tutorial

So, using the Python String find() method, we can search for substring as well as character, and if is there then we will get its index as a return value.

Finally, Python String Find Example | Find() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.