Skip to content

Module 7 · Strings — topic 12 of 22

replace()

replace(old, new, count) returns a copy with occurrences of one substring swapped for another. Learn the optional count, removing text, chaining replacements and the case-sensitivity of matching.

Beginner 10 min read·Lesson 93 of 306 in Python Programming

Learning objectives

  • Replace all or a limited number of occurrences
  • Remove text by replacing it with an empty string
  • Chain replacements safely

Definition

replace(old, new, count) returns a copy with occurrences of one substring swapped for another. Learn the optional count, removing text, chaining replacements and the case-sensitivity of matching.

Introduction

replace() finds every occurrence of a substring and returns a new string in which each one is replaced. "2026-11-22".replace("-", "/") gives "2026/11/22".

Why it matters

Cleaning and reformatting text constantly needs replacement: changing separators, removing unwanted symbols, fixing common typos, or filling a template such as “Dear {name}”.

Detailed explanation

replace() works on exact text, which makes it predictable: it never guesses. That is a strength for fixed substitutions such as separators and known symbols, and a limitation when the text varies, such as any number of spaces or any digit. Recognising which kind of problem you have tells you whether replace() or a regular expression is the right tool.

Each call scans the whole string, so a chain of ten replace() calls scans it ten times. For typical text this is fast; for very large documents, str.translate() or a regular expression can replace many characters in one pass.

replace(old, new) replaces every non-overlapping occurrence of old, scanning from left to right.

replace(old, new, count) replaces only the first count occurrences.

Replacing with "" deletes the substring: "1,20,000".replace(",", "") is "120000".

Matching is case-sensitive: "Python".replace("python", "Java") changes nothing.

If old is not found, the result is an unchanged copy; no error is raised.

Chained replacements run in order, so a later replacement can affect text produced by an earlier one. Order them carefully, or replace via a temporary marker when swapping two values.

For pattern-based replacements, such as all digits or repeated spaces, the re module (Module 15) is more powerful.

Syntax

Python
new_text = text.replace(old, new)
first_only = text.replace(old, new, 1)
removed = text.replace(unwanted, "")
  • All occurrences are replaced by default.
  • count limits how many are replaced.
  • The original string is unchanged.

Code examples

Replacing and removing

Python
print("2026-11-22".replace("-", "/"))
print("1,20,000".replace(",", ""))
print("banana".replace("a", "o", 2))
Output
2026/11/22
120000
bonona

Case-sensitive and not found

Python
text = "I like Python"
print(text.replace("python", "Java"))
print(text.replace("Python", "Java"))
Output
I like Python
I like Java

More examples

Cleaning prices and swapping words

Python
raw_prices = ["Rs 1,499", "Rs. 899", "Rs 12,000"]
clean = [int(p.replace("Rs.", "").replace("Rs", "").replace(",", "").strip()) for p in raw_prices]
print(clean, sum(clean))
sentence = "cats chase dogs"
wrong = sentence.replace("cats", "dogs").replace("dogs", "cats")
right = sentence.replace("cats", "#TMP#").replace("dogs", "cats").replace("#TMP#", "dogs")
print(wrong)
print(right)
Output
[1499, 899, 12000] 14398
cats chase cats
dogs chase cats

Step-by-step explanation

  • "Rs." is removed before "Rs" so the full-stop variant is handled first.
  • Commas are removed and strip() clears spaces before converting with int().
  • The wrong swap changes cats to dogs, then changes both dogs to cats.
  • Using a temporary marker keeps the first replacement from being undone by the second.

Expected output

Running “Cleaning prices and swapping words” prints exactly:

TextOutput
[1499, 899, 12000] 14398
cats chase cats
dogs chase cats

Practical applications

  • Data import scripts strip currency symbols and thousands separators.
  • Template systems replace markers such as {{name}} with real values.
  • Text editors implement find-and-replace with this exact operation.

Best practices

  • Order chained replacements carefully.
  • Use a marker when swapping two substrings.
  • Use regular expressions for whole-word or pattern replacements.

Common mistakes

Forgetting to save the result

Avoid

text.replace("old", "new")
print(text)

Prefer

text = text.replace("old", "new")
print(text)

replace returns a new string.

Replacing short substrings inside words

Avoid

"I can scan".replace("can", "will")

Prefer

Replace whole words only, for example with split() or the re module.

The first version gives "I will swill" because “can” also appears inside “scan”.

Key takeaways

  • replace(old, new, count) returns a new string with replacements.
  • Replacing with "" removes text.
  • Matching is exact and case-sensitive.

Try it yourself

  1. 1
    Convert "10:30:45" to "10h30m45s" using replace calls.
  2. 2
    Remove all spaces from a phone number such as "98 76 54 32 10".

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic