Generalize Your Substring Check
Previously you’ve worked with this text. It’s just a short text that contains the word secret a couple of times in different capitalizations, and you checked for the lowercase version by saying
text, and Python returned
True for that.
That’s because the lowercase letters and uppercase letters are different characters. So for Python, a lowercase
"s" is distinct from an uppercase
"S" in the same way that, for example, a lowercase
"s" and a lowercase
"x" are different.
So even though this is the same word for us as humans, it’s not the same string for the computer, which is why it returns
False, which means that if you were looking for a substring and it does occur in your text, but only with a specific capitalization, then you are going to get
False back from Python, even though for you as a human, the word that you’re looking for is actually in the text. For example, if I look for
"sEcReT" in what I call SpongeBob case,
Python is going to return
False because that specific capitalization of the word secret doesn’t appear in the text. So what you want to do to avoid this is just make sure that both the text and the substring have the same capitalization.
So for example, the text contains the word this, and the word this here is capitalized, so it starts with an uppercase T. Now if I were to look for
"this" in text, then Python is going to return
So I’m calling the
.lower() string method on the
text string. This is going to lowercase all of the characters in there, and therefore my check whether the substring
"this" is inside of the lowercase version of
text is going to return
03:07 and for the rest of the tutorial, we are going to continue working with this text that is all lowercase, because that avoids any sort of issues that might come from just capitalization being off.
03:32 Making sure that the capitalization of the substring and the string that you’re searching in are the same is going to help to make sure that you’re not accidentally not getting a match even though the word is inside of the string that you’re searching in.
03:54 And now that you know how you can find a substring in a string and how you can generalize the search a bit more, in the next lesson, you’ll take a look how you can learn a little bit more about the substring that Python identified.
Become a Member to join the conversation.