Методы find() и rfind() в Python
Метод find() в Python используется для поиска индекса подстроки в строке.
Эта функция возвращает наименьший индекс в строке, где подстрока «sub» находится внутри среза s [начало: конец].
Начальное значение по умолчанию – 0, и это необязательный аргумент.
Конечное значение по умолчанию – длина строки, это необязательный аргумент.
Если подстрока не найдена, возвращается –1.
Нам следует использовать метод find(), когда мы хотим узнать позицию индекса подстроки. Для проверки наличия подстроки мы можем использовать оператор in.
Примеры
Давайте посмотрим на несколько простых примеров метода find().
rfind()
Метод rfind() похож на find(), за исключением того, что поиск выполняется справа налево.
Как найти все индексы для подстроки
Строка find() и rfind() в Python возвращает первый совпавший индекс. Мы можем определить пользовательскую функцию для поиска всех индексов, по которым находится подстрока.
Python String find() Method
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found. (See example below)
Syntax
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The value to search for |
| start | Optional. Where to start the search. Default is 0 |
| end | Optional. Where to end the search. Default is to the end of the string |
More Examples
Example
Where in the text is the first occurrence of the letter "e"?:
txt = "Hello, welcome to my world."
Example
Where in the text is the first occurrence of the letter "e" when you only search between position 5 and 10?:
txt = "Hello, welcome to my world."
Example
If the value is not found, the find() method returns -1, but the index() method will raise an exception:
txt = "Hello, welcome to my world."

COLOR PICKER


Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Python String find() Method
find() is a Python library function that is used to find the index of the first occurrence of a substring from the given string. If find() is unable to locate the substring then it returns -1 instead of throwing an exception.
Before reading this article, understand the following Python programming topics:
Introduction
While creating software there are certain tasks that require us to search for some words/sentences, suppose you are making a text editor then one of the most important features is Find and Replace. For that, you have to search for words and even sentences in the document. In such scenarios find() function comes to the rescue.
find() function is a part of python library. find() takes a string as input. It is used to find the index of the first occurrence of the substring inside a given string. If the substring is not present then it returns -1 but it does not throw an exception.
Syntax of find() Function in Python
- string is the original sentence/word in which you want to look for the substring.
- substring is the sentence/word which you have to search.
- start and end are optional parameters. They specify the range where the substring needs to be searched.
What Does find() Python Return?
- If the substring exists in the string then it will return the index of the first occurrence of substring.
- If the substring does not exist then it will return -1.
Here is an example,
Output:
In this code, we created a string variable names paragraph and we called find() on it to find the occurrence of "I" and "q". Here, "I" comes at the very start of the string so its index 0 is returned, but in the second case "q" is not found, so we get -1
Let's look at different types of examples
1) No start and End Arguments are Given
Output:
Here we have create a variable str which contains a sentence and then we called find() on str and gave it 'python' as an argument. So, find() will search for 'python' in str and return the index of its first occurrence in str
When start and end arguments are not given then find() starts to look from the beginning and searches till the end of the string.
What if we use default arguments?
Output:
If you do not pass start and end arguments then their default values are used. The default value of start is 0 and the end is length of the string.
2) Start and End arguments are Given
Output
Here, we have made a variable called str and have stored a sentence in it. Then we call find() on it and gave it 'interests', 10 and 30 as arguments. 10 tells find() that it has to start looking for the substring (i.e interests) from the 10th position and 30 tells find() to look till the 30th position and not beyond that.
So, start and end arguments set a range and find() searches for the substring only in that range.
'interests' comes at 16th position, which is between 10 and 30 , so for the first print() the output is 16 and for the second it is -1 as 'interests' is not present between 30 and 40 .
3) Only Start Argument is Given
Output:
Here again we have stored a sentence in a variable called str and we call find() on str and pass 'interests' and 10 as arguments. 10 here tells find() that it has to start looking from the 10th index and since there is no end argument so it will look till the end of the string.
When only start is given then the end takes the default value i.e. length of the string automatically. So, here we define the starting range but not the ending range.
'interests' comes at 16th position, so for the first print() the output is 16 and for the second it is -1 as 'interests' is not present after 16 .
Can I find the position of a substring?
Yes you surely can.
Output:
In the find() you can pass a whole sentence as a input. Here we have passed 'very early' as input to find() and find() searchs for 'very early' in str and returns 10 as position of 'very early', which is the correct position.
Now What is rfind() in Python?
rfind() is similar to find() but there is a small difference. rfind() returns the highest index of the substring. Similar to find() it returns -1 if the substring is not found.
Its syntax is the same as find() and it also takes the arguments that find() takes.
Here is an example which will make things clear.
Output:
Here we fist created a string variable named myStr and called find() and rfind() on it. find() returned 0 and rfind() returned 9.
This is because, rfind() returned the index of the last occurence of 'py' while find() returned the index of the first occurence of 'py'.
Python String index()
index() function is also a library function of Python. This function gives the poisition of the substring just like find() but the difference is index() will throw a ValueError if the substring is not present in the string. In such a case, find() returns -1 .
Output:
Here you can see that find() returned -1 whereas index() threw an substring not found error.
How to Find Total Occurences of a Substring?
This is also a simple task, we can do this by using find() and a loop.
Output:
In this code, first, we have set the value of start and occurrences to 0 and then we used a for loop to iterate over the string repeatingStr .
Inside the loop we call find() to check if the substring 'repeating' is inside repearingStr or not.
If it is present then we add 1 to the value of start and increase the value of occurrences by 1 . The reason we add 1 to start is so that the substring is not counted twice.
Python find() – How to Search for a Substring in a String

Dionysia Lemonaki

When you’re working with a Python program, you might need to search for and locate a specific string inside another string.
This is where Python’s built-in string methods come in handy.
In this article, you will learn how to use Python’s built-in find() string method to help you search for a substring inside a string.
Here is what we will cover:
The find() Method — A Syntax Overview
The find() string method is built into Python’s standard library.
It takes a substring as input and finds its index — that is, the position of the substring inside the string you call the method on.
The general syntax for the find() method looks something like this:
Let’s break it down:
- string_object is the original string you are working with and the string you will call the find() method on. This could be any word you want to search through.
- The find() method takes three parameters – one required and two optional.
- «substring» is the first required parameter. This is the substring you are trying to find inside string_object . Make sure to include quotation marks.
- start_index_number is the second parameter and it’s optional. It specifies the starting index and the position from which the search will start. The default value is 0 .
- end_index_number is the third parameter and it’s also optional. It specifies the end index and where the search will stop. The default is the length of the string.
- Both the start_index_number and the end_index_number specify the range over which the search will take place and they narrow the search down to a particular section.
The return value of the find() method is an integer value.
If the substring is present in the string, find() returns the index, or the character position, of the first occurrence of the specified substring from that given string.
If the substring you are searching for is not present in the string, then find() will return -1 . It will not throw an exception.
How to Use find() with No Start and End Parameters Example
The following examples illustrate how to use the find() method using the only required parameter – the substring you want to search.
You can take a single word and search to find the index number of a specific letter:
I created a variable named fave_phrase and stored the string Hello world! .
I called the find() method on the variable containing the string and searched for the letter ‘w’ inside Hello world! .
I stored the result of the operation in a variable named search_fave_phrase and then printed its contents to the console.
The return value was the index of w which in this case was the integer 6 .
Keep in mind that indexing in programming and Computer Science in general always starts at 0 and not 1 .
How to Use find() with Start and End Parameters Example
Using the start and end parameters with the find() method lets you limit your search.
For example, if you wanted to find the index of the letter ‘w’ and start the search from position 3 and not earlier, you would do the following:
Since the search starts at position 3, the return value will be the first instance of the string containing ‘w’ from that position and onwards.
You can also narrow down the search even more and be more specific with your search with the end parameter:
Substring Not Found Example
As mentioned earlier, if the substring you specify with find() is not present in the string, then the output will be -1 and not an exception.
Is the find() Method Case-Sensitive?
What happens if you search for a letter in a different case?
In an earlier example, I searched for the index of the letter w in the phrase «Hello world!» and the find() method returned its position.
In this case, searching for the letter W capitalized returns -1 – meaning the letter is not present in the string.
So, when searching for a substring with the find() method, remember that the search will be case-sensitive.
The find() Method vs the in Keyword – What’s the Difference?
Use the in keyword to check if the substring is present in the string in the first place.
The general syntax for the in keyword is the following:
The in keyword returns a Boolean value – a value that is either True or False .
The in operator returns True when the substring is present in the string.
And if the substring is not present, it returns False :
Using the in keyword is a helpful first step before using the find() method.
You first check to see if a string contains a substring, and then you can use find() to find the position of the substring. That way, you know for sure that the substring is present.
So, use find() to find the index position of a substring inside a string and not to look if the substring is present in the string.
The find() Method vs the index() Method – What’s the Difference?
Similar to the find() method, the index() method is a string method used for finding the index of a substring inside a string.
So, both methods work in the same way.
The difference between the two methods is that the index() method raises an exception when the substring is not present in the string, in contrast to the find() method that returns the -1 value.
The example above shows that index() throws a ValueError when the substring is not present.
You may want to use find() over index() when you don’t want to deal with catching and handling any exceptions in your programs.
Conclusion
And there you have it! You now know how to search for a substring in a string using the find() method.
I hope you found this tutorial helpful.
To learn more about the Python programming language, check out freeCodeCamp’s Python certification.
You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce your understanding of the concepts you learned.