str.replace() Replace substring
Last updated: 2026-09-22
str.replace() Replace substring
str.replace(old, new[, count]) replaces old with new up to count times.
| Category | String Methods |
|---|---|
| Kind | Built-in Type Method |
| Python Version | all |
📝 Syntax
str.replace(old, new[, count])
⚙️ Parameters
| old Required | The substring to be replaced. |
|---|---|
| new Required | The replacement substring. |
| count Optional | Maximum number of replacements; -1 means replace all.(Default:-1) |
Returns:str. A copy with old replaced by new, up to count times.
Mutates the original:No (returns a new object)
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
bbb
bbaa
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QDoes replace() modify the original string?
ANo! Strings are immutable; replace() returns a new string. 'aaa'.replace('a', 'b') produces a new string while the original variable is unchanged; you must assign to capture the result.
QHow do I replace only the first few occurrences?
AUse the count parameter: 'aaa'.replace('a', 'b', 2) replaces only the first 2, giving 'bba'.
QWhat happens when the substring to replace does not exist?
ANo error; a copy of the original string is returned directly.
QHow do I delete a substring?
AReplace it with an empty string: 'a-b-c'.replace('-', '') gives 'abc'.