Prove That "a" Isn't in "AAA" (Solution)
00:00
The task is to prove that "a"
is not in "AAA"
, and I should do this in one line of code.
00:12
So again, use a call to print()
. So now you have to think about which string do you want to call the method on, right? And you want to find something inside of the "AAA"
string in that case, the larger string. That means that you are going to call the string method on "AAA"
.
00:31
So I’ll say "AAA"
, this is my string that I’m working with, and on it, call the method .find()
.
00:39
And then I need to pass .find()
an argument, and that argument is the substring that I’m trying to find, so in this case, that’s the lowercase "a"
.
00:47
So if I execute this, I should get -1
because the lowercase "a"
is not in the uppercase string "AAA"
. If you ran the same thing but passed in an uppercase "A"
here, then Python’s going to find it.
01:01 And do you know what the result’s going to be?
01:04 Try it out for yourself or take a guess.
01:08
In this case, the result is zero because .find()
returns the index of the first time that Python finds the substring in the string. So here, you’re getting the index of the first uppercase "A"
.
01:20 Well, if that string started with something else,
01:23
and I know I’m digressing a bit, but let’s take a look. If I say print()
, and then let’s say it’s a "BAA"
, so we have a sheep here, and then I search for uppercase "A"
in here, it definitely exists in the string, but it’s not on the first index position.
01:41
So do you know what you’re going to get? It’ll be 1
, because the index 1
is where Python finds the first time the substring that you passed in as an argument to .find()
.
01:53 All right? But that first line of code is the solution for the task. And I don’t know if I failed it now because I actually used three lines of code in my session, but those were just little digressions.
02:07
Anyway, just as a parting side note, despite the seemingly descriptive name of .find()
, there’s actually a better and more Pythonic way for finding a substring in a string, but it’s not a string method, so we won’t cover it in this course.
02:22 If you’re curious, check out the additional resources that I’ll share with you in the final lesson. Okay, let’s move on.
Become a Member to join the conversation.