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:15
The most basic way to replace a string in Python is to use the .replace()
string method. You can call the .replace()
method on any string, and it takes at least two arguments.
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.
00:37 If you don’t provide this argument, Python will replace all occurrences of the old string with the new string, and that’s what you want to do with your task at hand.
00:47 So you won’t see the third argument in this course.
00:51
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 str
object.
01:03
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 'Real Python'
.
01:17
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.
01:32
Let’s explore what this means. First, you define a variable named name
and set it with the string "Fake Python"
.
01:43
Now you can use .replace()
on name
and add the two strings, "Fake"
and "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 "Fake Python"
.
02:06
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 name
again.
02:25
Okay, now name
has the value "Real Python"
. Cool. By assigning the result of name.replace()
back to the name
variable, the value of name
was updated to "Real Python"
.
02:39
This distinction is crucial to keep in mind when working with the .replace()
method. When you use .replace()
on a string, the original value of the variable doesn’t change.
02:51
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.