Find a Letter in a String (Solution)
00:00
So the task talked about writing a program, which usually is an indicator that you should use a script for it. So again, I’ve opened up a new script and saved it as finder.py
, and then put in two, like, short notes.
00:11
I want to collect input and then display the results of searching for a letter. Let’s start by collecting input and saving that to somewhere. So my text
is going to be input("Enter text: ")
.
00:29
Then I want to display this result of searching for a letter in that text. So I want to say text.find()
, and then a letter. What is that letter? I don’t know.
00:40
I could search for just, like, a hard-coded letter—for example, "x"
—in here, and then print the result of that.
00:49
So let’s give that a spin. I’ll save and run it, and now I can enter a text. I will say Samantha
, and I get -1
because there’s no x
in Samantha
.
01:02
Now if I run the script again and try with a text that contains an x
—for example, xaid
—then I get 0
. So it finds x
at the first position.
01:14
So that works with x
, but I don’t think that’s great. If it will always look for x
, it’s maybe a little boring. So instead, I’m going to change this to allow the user to also input what character to search for.
01:28
So I’ll create another variable that I call character
, and that’ll be another call to input()
. And then I’ll say, "Enter character
to search for: "
.
01:41
And finally, I also need to replace the argument to text.find()
with character
, which then means it’ll be whatever the user input.
01:53
Technically, this user input could be more than a single character. .find()
works with substrings, so you could enter more than one character as a substring to search for.
02:03 If Python finds the substring, then it returns the index of the beginning of where the substring first shows up in the string. But for this exercise, you don’t have to worry about any of that.
02:13 You’ll assume that your users are good citizens and follow the instructions to only input a single character.
02:19
Let’s run that again. Enter text, so now I can say Samantha
again and search for a
, and then you can see that it finds it at the index position 1
, so at the second position, which is the index position one.
02:35
And let’s do it again, see whether it still works as expected. If I say Samantha
and search for x
, I got -1
. And one more test.
02:49
If I type in Samantha
and search for t
, then you can see I get 5
, which is the index position of the first t
that Python finds in the input string.
03:01 All right, so that works. Let’s clean up the script, remove the comments, and we’re done with this exercise.
Become a Member to join the conversation.