replace
- Python course
- Beginner
- Lesson 90/116
- 4 min
Learn text replacement with replace.
replace
replace replaces substrings in a string with another substring:
"hello world".replace("world", "Python")
# "hello Python"By default it replaces all matches. A maximum count can be given as a third parameter:
"a-b-c".replace("-", "+", 1)
# "a+b-c"replace also returns a new string; it does not modify the original.
Limiting replace count
The third parameter limits how many replacements happen:
"a-b-c-d".replace("-", "+", 2)
# "a+b+c-d"This is useful when you only want the first N changes. For example, to change the first separator in a file path.
If no third parameter is given, all matches are replaced.
Practice Replace a substring
Assign "hello world" to text. Assign text.replace("world", "Python") to result. Then print print(result).
Starter code
# Replace a substringSample solution
text = "hello world"
result = text.replace("world", "Python")
print(result)Expected output
hello Python
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does "hello".replace("l", "L") return?
- "heLlo"
- "heLo"
- "hello"
- "heLLo" Correct answer
Explanation: All 'l' letters become 'L'.
2 Complete the replace call
result = "hello world".____("world", "Python")
result = "hello world".replace("world", "Python")
Explanation: replace("world", "Python") replaces the substring.
3 Match the replace parts
| Term | Meaning |
|---|---|
replace |
Replace method |
first parameter |
Searched substring |
second parameter |
New substring |
third parameter |
Maximum count |