Use .count() to Get the Number of Occurrences
00:00
So here you have the lowercased version of the text that we were working with, and you identified that the substring "secret"
appears in this text. But, for example, you don’t really know how often is it in there, right? If you want to know that, then you can use .count()
.
00:17
You can say text_lower.count()
and then pass in the substring as an argument here. That would be "secret"
.
00:28
And then Python will return an integer that tells you how often did it find the substring inside of that string. You can count this manually here too. You can see that here’s "secret"
once, twice, three times. And then, the fourth time might be a little surprising, but it’s down here, and it’s part of the word "secretly"
. Now, keep in mind that for Python, any character is just a character, so the whitespace character doesn’t really have the meaning that it has for us by delimiting a word. It’s just another character.
00:59
So Python looks through the string, through every character, including the whitespaces, and looks if this substring appears somewhere. And also here in the word "secretly"
, you have the substring "secret"
, so that becomes part of the count. Now, there are some tricks that you could do.
01:15
For example, if you really wanted just the word "secret"
, you could include the white space characters in your search, and then Python is only going to find it once, and that is over here, all right.
01:27
And you can see already that if you really wanted to find all the word "secret"
01:32 but ignore that here’s a comma, and here’s a period, and here’s like two whitespaces left and right, and then maybe exclude this one because it has some characters after it, that gets a bit complicated here, right?
01:46
So if you want to search with these sorts of conditions, then there’s a better way of doing that, and you’ll learn about that in a couple lessons down the road. But for now, .count()
can give you an information of how often is the substring really inside of the string that you’re searching in.
02:04
Now that you know that there’s four substrings "secret"
inside of the text_lower
, you might be wondering when you typed "secret" in
text_lower
, which of those did Python really find?
02:20 The quick answer to that is that it’s the first occurrence, but let’s look a little closer to find out a bit more information about that in the next lesson.
Become a Member to join the conversation.