Python String replace()
Method
The replace() method in Python is used to replace parts of a string with another string. It’s a very useful and beginner-friendly tool for text processing.
Syntax
string.replace(old, new, count)
Parameters:
old
– The substring you want to replace.new
– The substring you want to replace it with.count
(optional) – The number of times you want to replaceold
withnew
. If omitted, all occurrences are replaced.
Returns:
- A new string with replacements applied. The original string is not modified.
Example 1: Basic Replacement
text = "I love apples"
new_text = text.replace("apples", "bananas")
print(new_text)
I love bananas
Example 2: Replace All Occurrences
quote = "ha ha ha!"
print(quote.replace("ha", "ho"))
ho ho ho!
Example 3: Replace Only First Occurrence
data = "one one one"
print(data.replace("one", "two", 1))
two one one
Use Cases of replace()
- Correcting typos in strings
- Formatting text
- Removing unwanted characters (e.g.,
replace(",", "")
to remove commas) - Replacing sensitive or restricted words
Common Mistakes
- Strings are immutable:
replace()
returns a new string – it does not change the original. - Trying to replace a substring that doesn't exist has no effect (no error).
- Remember that it's case-sensitive:
"hello".replace("H", "J")
does nothing.
Interview Tip
Use replace()
when cleaning strings or doing simple data transformations. It’s often seen in string manipulation questions or during preprocessing.
Summary
replace()
is used to replace parts of a string with a new value.- You can specify how many times to replace with the optional
count
parameter. - Returns a new string; the original remains unchanged.
Practice Problem
Write a program to replace all spaces in a sentence with dashes -
.
sentence = input("Enter a sentence: ")
print(sentence.replace(" ", "-"))