Reference

Reference · Strings

str.replace()

str.replace() returns a new string with occurrences of a substring swapped for another. By default it replaces every match; a count argument caps how many are changed. The original string is never modified.

XCODXReference · Updated

Definition

str.replace() returns a new string in which every occurrence of a substring has been swapped for another. It is the standard tool for substitution: fixing a typo throughout some text, normalising a delimiter, or blanking out a token. Because strings are immutable, replace() cannot edit the string in place — it always builds and returns a fresh one, and the original is left exactly as it was.

Two defaults define its behavior and both surprise newcomers. First, it replaces all matches, not just the first — a whole-string sweep by default. Second, it does nothing destructive to the original: if you forget to capture the return value, your change is simply lost. Keep both in mind and replace() is entirely predictable. It performs a plain literal match, not a pattern match, so the text you pass is found verbatim.

Syntax

str.replace(old, new, count=-1)

# old:   the substring to search for (matched literally)
# new:   the replacement substring
# count: optional cap on how many occurrences to replace; -1 means all

Parameters

ParameterDefaultDescription
oldrequiredThe substring to look for. It is matched literally, not as a regular expression, so characters like . or * have no special meaning. If it is not present, the string is returned unchanged.
newrequiredThe replacement substring, inserted wherever old was found. It may be the empty string '', which deletes each match instead of substituting it.
count-1The maximum number of occurrences to replace, scanning left to right. The default -1 means replace every match. A value of 0 replaces nothing and returns the original text; 2 replaces only the first two.

Return value

A new string with the replacements applied. The original string is unchanged, so you must assign the result to keep it. When old does not occur, the method returns the original string object; when it does, you get a freshly built string.

  • By default every match is replaced, left to right.
  • A count of n replaces at most the first n matches and leaves the rest.
  • An empty new deletes each matched substring.
  • Matching is literal — old is never treated as a pattern.

Examples

Replace every match (the default)

s = "one fish two fish"
print(s.replace("fish", "cat"))  # 'one cat two cat'

Cap replacements with count

s = "a-a-a-a"
print(s.replace("-", "_", 2))  # 'a_a_a-a' — only the first two

The original is never modified

s = "hello"
s.replace("l", "L")   # result discarded
print(s)              # 'hello' — unchanged
s = s.replace("l", "L")
print(s)              # 'heLLo' — captured

Delete a substring with an empty replacement

s = "1,000,000"
print(s.replace(",", ""))  # '1000000'

Chain replacements left to right

word = "color, flavor, honor"
british = word.replace("color", "colour").replace("flavor", "flavour").replace("honor", "honour")
print(british)  # 'colour, flavour, honour'

Normalise Windows line endings

text = "a\r\nb\r\nc"
clean = text.replace("\r\n", "\n")
print(repr(clean))        # 'a\nb\nc'
print(clean.split("\n"))  # ['a', 'b', 'c']

Build a slug by replacing spaces

title = "My First Blog Post"
slug = title.lower().replace(" ", "-")
print(slug)  # 'my-first-blog-post'

count=0 changes nothing; count=1 hits only the first

s = "na na na"
print(s.replace("na", "NA", 0))  # 'na na na'  — nothing replaced
print(s.replace("na", "NA", 1))  # 'NA na na'  — first only

Because replace() returns a new string, calls chain naturally: s.replace('a', 'b').replace('c', 'd') applies two substitutions in sequence, each acting on the result of the last. That reads cleanly precisely because no step mutates anything shared.

Browser & runtime support

Difference from JavaScript's replace()

If you are coming from JavaScript, the default is the opposite of what you expect. JavaScript's String.prototype.replace() with a plain string replaces only the first match, and you need a global regex (or replaceAll) to hit every one. Python's str.replace() inverts that: it replaces all matches by default, and you pass a count to *limit* it. So the mental switch is that Python is all-by-default while JavaScript is first-by-default — a frequent source of confusion when porting code between the two languages.

Availability

str.replace() is a core string method present in every version of Python 3 with no import required. Its signature — including the optional count argument — has been stable for the entire Python 3 line and is safe to rely on across every maintained interpreter.

Frequently asked questions

Does str.replace() change the original string?
No. Strings are immutable, so replace() returns a new string and leaves the original untouched. You must assign the result, e.g. s = s.replace('a', 'b'), to keep the change.
Does Python replace all occurrences or just the first?
All of them by default. Unlike JavaScript's string replace(), which changes only the first match, Python's str.replace() replaces every occurrence unless you pass a count to limit it.
How do I replace only the first occurrence in Python?
Pass a count of 1: s.replace(old, new, 1) replaces just the first match and leaves the rest unchanged.
How do I delete a substring with replace()?
Replace it with the empty string: s.replace(',', '') removes every comma. Every matched piece is dropped rather than substituted.