Python Reference ยท String Methods
Python str.replace() method
Reference for Python str.replace(): return a copy of a string with substrings replaced, the optional count argument, empty-string behavior and common mistakes.
The str.replace() method returns a new string in which every occurrence of one substring is replaced by another. You can limit how many replacements happen with an optional count.
Strings are immutable, so replace() never changes the original. A very common mistake is calling it and throwing the result away.
print("a-b-c".replace("-", "+")) # a+b+c
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.replace(old, new) str.replace(old, new, count)
| Name | Description |
|---|---|
old |
The substring to look for. |
new |
The text to put in its place. It can be empty to delete matches. |
count |
Optional. Replace only the first count occurrences. A negative value (the default, -1) means all of them. Since Python 3.13 it may be passed as a keyword. |
Return value: a new string.
Raises: TypeError if an argument is not a string or count is not an integer.
Usage notes
- Returns a copy. Assign the result:
s = s.replace(...). - Matches are found left to right and do not overlap.
"aaaa".replace("aa", "b")gives"bb", and the replacement text is not searched again. - Case-sensitive. For case-insensitive replacement use
re.sub(..., flags=re.IGNORECASE). - Empty
oldmatches between every character and at both ends, so"abc".replace("", "-")gives"-a-b-c-". This is rarely what you want. - Literal text only. Characters such as
.or*have no special meaning; use theremodule for patterns. - Many single-character swaps are faster with
str.maketrans()andtranslate(), and chainedreplace()calls can interfere with each other (replacingawithband thenbwithc). - Tidying whitespace:
" ".join(s.split())collapses runs of whitespace, whichreplace()cannot do in one call. - Also available on
bytesandbytearray(the latter returns a new object).