Replace a String With .replace()
00:00 To clean up the swear words and the transcript, you need to replace the swear word with another word—or, to phrase this as an explicit task for you as a Python developer, you need to replace a string with another string.
00:26 The first argument is the old string that you want to replace, and the second is the replacement. You can optionally provide a third argument, which is the number of replacements you want to make.
At the bottom of this slide, you can see an example of the
.replace() method with two arguments. There is a string saying
"Fake Python", and you’re calling the
.replace() method on the
The first argument is the string
"Fake. That’s the string you want to replace. And the second argument is the string
"Real". That’s the string you want to replace the word
"Fake" with. The output in the shell is
That’s much better than Fake Python, in my opinion, but obviously I’m biased. Anyway, there is one important detail here. Although the Python shell displaced the result of
.replace(), the string itself stays unchanged.
Now you can use
name and add the two strings,
"Real", as arguments. When you hit Enter, you can see the output
'Real Python'. If you had to guess, what do you think the value of
name is now?
"Real Python"? Well, actually not. The variable
name still has the value of
When you use the
.replace() method on a string, the original value of the variable doesn’t change. So what can you do instead? If you assign the result of
name.replace() back to the
name variable, the value is updated accordingly. Let’s check
So remember that you always need to assign the result of
.replace() to a variable if you want to continue to work with the output. Okay, now that we’ve got this covered, it’s time to apply this knowledge to the chat transcript.
Become a Member to join the conversation.