Finding a String in a String
One of the most useful string methods is
.find(). As its name implies, this method allows you to find the location of one string within another string, commonly referred to as a substring. To use
.find(), you tack it on the end of a variable or string literal, with the string you want to find typed between the parentheses.
"I put a string inside your string". So in this particular case, when you say
new_phrase.find(), what will you get if you type in
"string"? So in this case, it’s just the first occurrence. It did not return the second one. That returns the index only of the first occurrence starting from the beginning of the string. And note, if you had a string, let’s say of a phone number …
Sometimes you may want to replace all the occurrences of a particular string within a string. Since
.find() returns the index of the first occurrence of a substring, you can’t easily use it to perform this operation.
But strings have a
.replace() method that replaces each instance of a substring with another string. Just like the method
.find(), you tack
.replace() onto the end of a variable or a string literal.
Okay. And in this case you wanted to replace using
.replace(), and you can see here, it says, put in the old, meaning the substring you’re looking for, to be replaced by the new string. So I’ll say, look for
"the truth" and replace it with
Kind of cool. Now what happened to
my_story itself? You might remember that strings are immutable objects, and
.replace() won’t alter the
my_story variable. And using the
.replace() method doesn’t alter the string
my_story, if you immediately type
my_story into the interactive window, you’ll see that. If you wanted to change the value of the string
my_story, you need to reassign it. So again, a bit of a refresher on this: you would say, I would like to assign
my_story to, in this case, this replacement. So you’d say, let’s say we want to do the same thing, exchanging
"the truth" for
.replace() method replaces every instance of a particular substring with the replacement text. Now, if you want to replace multiple different substrings within a string, then you need to use
.replace() multiple times.
It’s time to challenge yourself with some new review exercises. In one line of code, display the result of trying to find the substring lowercase,
"a" in the string of
"AAA". Note, the result should be a
Replace every occurrence of the character
"x" in the string
"Somebody said something to Samantha." Write a program that accepts user input with
input() and then displays the result of trying to find a particular letter in that input.
Here’s another, bigger challenge for you. This one is going to require you to write a program, turning your user into elite hacker. Write a program called
translate.py that asks the user for some input.
Become a Member to join the conversation.