The index and find functions return the position of a character or a substring inside a string. They both take a single parameter, that is required. The two additional parameters: __start and __end are optional.
my_string = 'This is a string' print(my_string.find('s')) print(my_string.index('s'))
Both functions work the same way if the character is present inside the string. Indexing in Python starts from 0, so the 4th element in a string has index 3.
The difference between these two functions is when the element we are looking for a character that is not in the string.
In the case of the find function, the result is -1.
The index function works differently.
It raises an error if there is no character present inside the string.
ValueError: substring not found
Handling the exception
Of course, exceptions can be handled. If we modify the code, the index function works the same as the find function.
my_string = 'This is a string' try: index = my_string.index('x') except ValueError: index = -1 print(index)
If you run the code for “x”, Python will raise an error, and the code inside the except clause will be executed. Then it will print the value: -1.
Index of a Substring
So far, I showed you how to find the index of a character.
Similarly, you can find the index of a substring.
my_string = 'This is a string' print(my_string.find('str')) print(my_string.index('str'))
The “str” substring is at position 11, therefore the index is 10.
As I mentioned earlier, both functions can take up to three parameters. Let’s take a look at how it works for two arguments.
my_string = 'This is a string' print(my_string.index('s', 7)) print(my_string.find('s', 7))
The second parameter tells the function at which index it should start searching for the matching index. Because there is no __end parameter present, it looks from the index 7 to the end of the string. In this case, it returns index 10.
If you add both: the __start and the __end parameters, Python will look for matching indexes between these two numbers.
my_string = 'This is a string' print(my_string.index('s', 4, 7)) print(my_string.find('s', 4, 7))
In our case, it returns 6.
If the character is not present in this range, the find function will return -1 and the index will raise an error the same way as before, even if the character is in a string, but outside the range.
Get all positions
So far, we have tried to find a position of a string, and when the function finds it, it stops and returns the index.
If we want to find all the indexes, not only the first one, we can use list comprehension. It’s a simple compact, one-line solution that can replace the for function.
my_string = 'This is a string' def find(my_str, my_char): return [i for i, ltr in enumerate(my_str) if ltr == my_char] my_list = find(my_string, 's') print(my_list)
All indexes are added to a list.
[3, 6, 10]
Get the last index
So far, I have written about searching for an index from the start of the string.
But, we can also search for the end of the string to the beginning, so instead of getting the first index, we will get the last one.
One way to do it is to search for all indexes as we did in the previous example. Then, instead of printing all elements in the list, we are going to print only the last one.
This is the result, the code is going to return – the last index.
We can take a different approach. First, reverse the string and then look for the first element to get an index.
my_string = 'This is a string' my_string = my_string[::-1] print(my_string.find('s'))
This code is going to return 5.
Now, we have the last element, counting from the end, instead of the beginning. The statement [::-1] means to start at the last element of the string and end at position 0, and move with step -1, which means one step backward.
We have to count all elements inside the string and subtract the position of the element counted from the end (5). This will give us the position of the last matching element. Because indexing starts from 0 and not 1, we have to subtract 1.
my_string = 'This is a string' my_string = my_string[::-1] print(len(my_string) - my_string.find('s') - 1)
The last element inside the string is 10.