Use .index() to Get the Location of the Substring
So I’ve quickly mentioned at the end of the last lesson that the substring that Python finds when you just do a substring check using the
in operator is the first one, so the first occurrence of the substring in your string.
00:13 Now maybe you want to know where in the string does it appear. And for that there is a handy string method that you can use to find the index position of that first occurrence of the substring.
It is aptly named
.index(). So you can say
text_lower.index() and then pass it as an argument the substring, and then Python will return to you the index position of the first letter of the first occurrence of the substring in your string.
So here you get position
59, and that means that here at position 59 is where the first occurrence of the substring
"secret" starts inside of this text up here. Okay, so
.index() gives you a way to get a bit more information about where’s the substring located. It also takes optional parameters.
01:05 You can give a start index and an end index, so where in the string you want to search for. So this always, if you start at the beginning, which is the default, you’re always going to find the first occurrence.
01:15 But if you want to start somewhere after 59, then it’s going to give you the beginning position of the next one.
Let’s give it a quick spin just so that you see how that works. You can say
text_lower.index(), then pass it
"secret", and then here I’m going to give it a different start position.
I’m going to say start at
60. If I don’t define the end, then it’s just going to go to the end of the string. So in this case, it’s going to start searching here for the string
"ecret" is not the string
"secret", so the first one it’s going to find is just going to be a little after that, and you will get the position
66, which is where the second occurrence of
"secret" in that case starts in your string. And yeah, like I mentioned, you can also define the end.
02:03 So if you just want to search within a specific part of your string, then it’s kind of like a slice syntax that you can pass in here. And this can give you additional information about where inside of your string is the substring located. In the next lesson, I’m going to show you one more string method that is often a little misused for doing the substring check in Python, and I’ll show you how it works and also why it’s not the best way of doing that check.
Become a Member to join the conversation.