Python String finds function returns the lowest index of the substring if the value (substring) found in given sentences. If it’s is not found then, it returns a -1 integer value. The find() function similar to the index() function,
The only difference is that the
index() function throws an exception if the value is not found. In this tutorial, you will learn about find functions and multiple examples.
A simple syntax for find string in python.
string.index(value, start, end)
- value – string (substring) to search | Required
- start – Here to start the search otherwise Default is 0 | Optional
- end – Where to end the search. The default is to the end of the string | Optional
Return Value from find()
The find() function returns an integer value. If substring finds in a sentence, then it returns the lowest index else returns.
Python string find() Function Examples
It’s a simple example to find a string (pass only value) in a sentence and print the index number in the console.
sentence = 'Python programming tutorial.' result = sentence.find('Python') print('Substring found at index :', result)
Output: Substring found at index : 0
If not found substring Example
Another example to find a substring in a sentence, where substring not in the sentence.
sentence = 'Python programming tutorial.' print(sentence.find('eyehunt'))
Output : -1
Where in the same situation index() function will throw an error?
find() With start and end Arguments
find a “t” in a sentence from start 5 to end 20 rang.
sentence = 'Python programming tutorial.' # Substring is searched in 'programming tu' result = sentence.find('t', 5, 20) print('Substring found at index :', result)
Output: Substring found at index: 19
Note: Python is case sensitive language, check this example, first “P” (uppercase) latter ignored.
sentence = 'Python programming tutorial.' result = sentence.find('p') print("index is :", result)
Output : index is : 7
Do comment if you have any doubt and suggestion for this tutorial. We like to hear from you.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python String Find Examples are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.