Python String Find

python-find-method-1

To find a string in a string, Python String find () method, is  the first string method that we can use is Python. With String find () method, we can find any string in a given string. There are three parameters in find() method. These are:

 

  • Value
  • Start
  • End

 

The value is the mandatory part fort his method. It is the string that we are looking for. Beside this parameters, there is also a start and end parameter. These paramaters are the indexes that can be mentioned before this search. This means that look for between these indexes if Python String Contains it or not.

 

The output of Python String find is the first index value of the string. If it does not find the value, it returns with -1.

 


You can also learn Python String Concatenation


 

Let’s do an example about  find () method used with python strings.

 

msg = "I like cats."
print(msg.find("cats"))

 

The output of this code is :

 

7

 

You can also watch the video of this lesson!

 

python-find-method-1

 

Now, let’s see this example that find() method will not find the string.

 

msg = "I like cats."
print(msg.find("dogs"))

 

The output of this python code will be:

 

-1

 

python-find-method-2

 

 

We can also define the other parameters of this fucntion. Here, we will define start and end index like below:

 

msg = "I like cats."
print(msg.find("cats",7,11))

 

The output of this python string find code will be:

 

7

 

python-string-find-ipcisco.com-1

 

But what if we change these indexes? For example let’s change firstly the end index.

 

msg = "I like cats."
print(msg.find("cats",1,5))

 

Because of the fact that the string that we are looking  for starts at index 7 and go through index 11, when we change this end index, it will not find it . So the output will be:

 

-1

 

python-string-find-ipcisco.com-2

 

It will give the same output for the below code also. Because it is not containing 7-11 indexes.

 

msg = "I like cats."
print(msg.find("cats",4,10))

 

-1

 


You can also learn Python String Replace method.


 

In this lesson, we have learned an imporntat method used in python to find any string in a string. In other words we have learned Python String find function with example.

 

 

Back to: Python Programming Course > Python Strings

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand
Latest Blog Posts