Skip to content
Tutorials Center
My learning

Topics

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.

Python
print("a-b-c".replace("-", "+"))   # a+b+c

Try it

Python Replacing text

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.

Python Edge cases

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

Python
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 old matches 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 the re module for patterns.
  • Many single-character swaps are faster with str.maketrans() and translate(), and chained replace() calls can interfere with each other (replacing a with b and then b with c).
  • Tidying whitespace: " ".join(s.split()) collapses runs of whitespace, which replace() cannot do in one call.
  • Also available on bytes and bytearray (the latter returns a new object).