Learning the replace() Method for Strings


In this tutorial, you’ll learn how to use the replace() method in Python to modify text in strings. By the end, you’ll be able to replace words, letters, or characters in any string!


1. What Is the replace() Method?

The replace() method is used to replace parts of a string with something else.
Here’s how it works:

string.replace(old, new)



2. Basic Example

Let’s start with a simple example:

message = "Hello, world!"

new_message = message.replace("world", "Python")

print(new_message)


Output:

Hello, Python!


In this example:


3. Replacing Letters

You can also replace individual letters:

word = "apple"

new_word = word.replace("a", "o")

print(new_word)


Output:

opple



4. Replacing Multiple Words

If the word appears more than once, replace() will replace all occurrences:

sentence = "The cat sat on the cat."

new_sentence = sentence.replace("cat", "dog")

print(new_sentence)


Output:

The dog sat on the dog.



5. Limiting Replacements

You can limit how many times replace() makes changes by adding a third argument:

text = "banana banana banana"

new_text = text.replace("banana", "apple", 2)

print(new_text)


Output:

apple apple banana


In this example:


6. Practical Uses

Example 1: Fixing Typos

sentence = "I lvoe Python!"

fixed_sentence = sentence.replace("lvoe", "love")

print(fixed_sentence)


Output:

I love Python!


Example 2: Censoring Words

comment = "This is a bad word!"

censored = comment.replace("bad", "***")

print(censored)


Output:

This is a *** word!



7. Practice Exercises

Exercise 1: Fix a Sentence

The sentence I like bannanas has a typo. Write a program to replace "bannanas" with "bananas".

Exercise 2: Replace Words

Write a program that replaces the word "dog" with "cat" in the sentence:
The dog barked at the other dog.

Exercise 3: Replace Letters

Write a program that replaces all the "e"s with "a"s in the word:
elephant

Exercise 4: Limit Replacements

Write a program to replace the first two "hello"s with "hi" in the text:
hello hello hello hello


8. Bonus Challenge

Create a program that censors multiple words:

Input:

This is bad, ugly, and mean!  


Output:

This is ***, ###, and @@@!  



9. What’s Next?

Great job learning about the replace() method! It’s a powerful tool you can use in text-based projects like creating chat apps, fixing typos, or customizing messages. Keep practicing! 🎉