The Python string find() method is used to check if a string is a substring of another string.
Often, when we want to check if a string contains another string,
find() is very useful to solve this problem.
Let us understand how we can use this, through some simple examples.
Syntax of Python String Find()
ret = str.find(sub, start, end)
Here, find() is invoked on a string object
str and returns an Integer. This checks if the substring
sub lies between
end, which are optional parameters.
start is included, and
end is not included.
find() does not take keyword arguments, so you must only mention positional arguments.
If the substring does not exist between the positions, then
-1. Otherwise, it is the position of the first match of the substring on the input string.
Let’s look at a simple example.
test_string = "Hello from AskPython" # We will check if the substring # 'AskPython' exists in test_string print(test_string.find('AskPython', 0, len(test_string)) )
Since the substring exists, the position of the first character of the substring (‘A’ in ‘AskPython’) is returned, which is 11.
We can also use negative indexing to mention offsets from the end of the string. For example,
test_string = "Hello from AskPython" # Will search from the first to the # second last position print(test_string.find('AskPython', 0, -1)) # Will search from index 5 to len(str) - 1 print(test_string.find('from', 5, -1))
For the first instance, the output is negative because the find() method cannot entirely match the string “AskPython”.
The reason being that because of the -1, the find string is only searching until AskPytho, which means what we’re searching for isn’t really found.
Using Python String find() Without Start/End Arguments
We can leave the
end arguments empty, if we wish to search across the whole string. This is the most widely used way of using Python string find() by many programmers.
We can rewrite our previous example as:
test_string = "Hello from AskPython" print(test_string.find('AskPython'))
This will give the same output as before.
Using find() With Only start Argument
We can only specify the starting position, until the end of the string, by leaving out the
test_string = "Hello from AskPython" # Will print 11 print(test_string.find('AskPython', 0)) # Will print -1, as the search starts # from position 12, i.e from 'k' print(test_string.find('AskPython', 12))
In this article, we have learned about the
str.find() method to search for substrings.
- Python Documentation for String.find()