Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Chain the .replace() Method

00:00 Here you have the chat transcript again. I already assigned the content of the chat transcript to a variable named transcript. To make the code more readable, you can use triple-quote syntax (""") to define a multiline string.

00:15 Also, note that you put a backslash (\) after your triple quotes. Without the backslash, you would have a new line at the beginning of your transcript. With the backslash, you can put the transcript nicely looking into three lines after the triple quotes, and put the backslash after the triple quotes to say, like, Hey, Python, I know there is a new line, but please remove it. Now, you can use the .replace() method to replace the uppercase word "BLASTED" with a more polite word or a huffing emoji. When you press Enter, then you can see the output in the shell.

00:48 The word "BLASTED" is replaced with the huffing emoji,

00:52 but there is still another occurrence of "blast" in the last message from John Doe. That’s not surprising because the .replace() method only replaces the exact string you provide as the first argument.

01:04 So even if the case of one letter doesn’t match, it’ll prevent any replacements in your transcript because there are no words that match this exact case.

01:14 This means that if you are using the .replace() method, you’ll need to call it various times with the variations. In this case, you can just chain on another call to .replace(). So let’s do it again.

01:28 transcript.replace(), "BLASTED" in uppercase, huffing emoji, and another call to .replace() with the word "Blast" and the huffing emoji again.

01:37 When you press Enter, then you can see that the output is now exactly what you want. Both the uppercase "BLASTED" and the word "Blast" are replaced with the huffing emoji. But keep in mind, since you didn’t assign the output from .replace() to a new variable, the original transcript still stays the same. And yeah, now we replaced this swear word, but there are other things we need to sanitize.

02:01 So we would have to place another .replace() on another .replace(), and so on. So you might be thinking that there is a better way to handle this, especially for a general-purpose transcription sanitizer like the one you want to create for your work at hand, right?

02:18 So instead of manually typing out .replace() every time, you may want to explore a more efficient approach. And you know what? There is a more efficient approach.

02:29 Hop along to the next lesson to learn more about it.

Become a Member to join the conversation.