Python String Replacement

In the last lesson you learned String Searching. There you found out where a piece of text sits inside a string. Finding it is only one half. Now comes the other half. What if you want to change that text? Maybe swap a word. Maybe fix a typo. Maybe clean up messy data. That is what this lesson is about.

πŸ€” Why You Need String Replacement

Here is the pain. You get some text from a user or a file. It is not in the shape you want. A phone number has dots where you need dashes. A name has the wrong spelling. A sentence has a placeholder word you need to fill in.

You could try to do this by hand, one character at a time. That is slow. It is also easy to get wrong. The fix is one clean tool: the replace() method. You tell it the old text and the new text. It gives you back the fixed string.

🧩 What replace() Does

Think of replace() like find-and-replace in a word processor. You type the word you want gone. You type what should take its place. The editor swaps every match for you. The replace() method does the same thing, but in code.

The syntax is simple. You call replace() on a string and pass it two things:

new_string = old_string.replace(old_part, new_part)
  • old_part is the text you want to find.
  • new_part is the text you want to put there instead.
  • replace() hands back a brand new string with the swap done.

Here is a small example. We take a greeting and swap one word.

message = "Hello, World"
result = message.replace("World", "Python")
print(result)

Output

Hello, Python

See how "World" became "Python"? You said what to find. You said what to put there. Then replace() did the work.

⚠️ Strings Don’t Change Themselves

Now this is the part that trips up almost everyone the first time. In Python, strings are immutable. That word means they cannot be changed after they are made. So replace() does not edit your original string. It builds a new one and returns it.

That means you have to catch the result. If you do not store it, the work is thrown away.

Look at this common bug:

name = "Jonh"
# ❌ Avoid: calling replace but not storing the result
name.replace("Jonh", "John")
print(name)

Output

Jonh

The typo is still there. Why? Because replace() returned a fixed string, but nobody caught it. So it just vanished. The original name never changed.

Here is the right way. You store what replace() gives back.

name = "Jonh"
# βœ… Good: store the returned string
name = name.replace("Jonh", "John")
print(name)

Output

John

Tip

A simple rule to remember: replace() gives you a new string. It never changes the old one. So always assign it to something, like text = text.replace(...).

πŸ” Replacing Every Match

By default, replace() does not stop at the first match. It swaps every match it finds in the string. So one call can fix many spots at once.

Say we have a sentence where someone typed β€œcat” but meant β€œdog” everywhere. One call fixes all of them.

sentence = "The cat sat with another cat near the cat door"
fixed = sentence.replace("cat", "dog")
print(fixed)

Output

The dog sat with another dog near the dog door

All three appearances of "cat" turned into "dog". You did not have to loop or count. replace() walked the whole string for you.

πŸ”’ Limiting How Many You Replace

Sometimes you do not want to change every match. Maybe you only want to fix the first one or two. replace() takes an optional third number for that. It tells the method the most number of swaps to make.

The syntax looks like this:

new_string = old_string.replace(old_part, new_part, count)

That count is the limit. Here we have three matches but we only want the first two changed.

text = "one one one"
result = text.replace("one", "two", 2)
print(result)

Output

two two one

The first two "one" words became "two". The third was left alone because we hit our limit of 2. This is handy when only the early matches matter, like fixing the first line of an address but leaving the rest.

Here is a quick summary of the three pieces you can pass.

Argument What it means Required?
old The text to find Yes
new The text to put in its place Yes
count The most swaps to make No, all matches by default

πŸ”— Chaining a Few Replaces

Because replace() returns a string, you can call replace() again right on that result. This is called chaining. It lets you do several cleanups in one smooth line.

Say Alex pasted a value with the wrong symbols. We need to drop the dollar sign and the commas to get a clean number.

price = "$1,299"
clean = price.replace("$", "").replace(",", "")
print(clean)

Output

1299

Read it left to right. First .replace("$", "") removes the dollar sign. Notice the new text is an empty string "". That is a neat trick to delete something. Then the result of that flows into the next .replace(",", ""), which removes the comma. Two cleanups, one line.

Note

Replacing with an empty string "" is how you remove text. There is no separate β€œdelete” method. You just replace the unwanted part with nothing.

🧹 A Real Cleanup Example

Let me show you something you will actually do at work. Riya gives you a phone number, but she typed dots between the groups. Your system wants dashes instead.

phone = "555.123.4567"
formatted = phone.replace(".", "-")
print(formatted)

Output

555-123-4567

One call, and every dot became a dash. Clean.

The same idea fixes dates. Someone sends a date with slashes but your database wants dashes. Same one-line move.

date = "2026/06/12"
fixed_date = date.replace("/", "-")
print(fixed_date)

Output

2026-06-12

This kind of small cleanup is everywhere in real code. Data almost never arrives in the exact shape you want. So a quick replace() to fix separators is one of the most common things you will write.

🚧 Common Mistakes

A few things tend to catch people. Watch for these.

  • Forgetting to store the result. text.replace(...) on its own does nothing useful. Write text = text.replace(...).
  • Expecting it to change the original. It never does. Strings stay the same. You get a new one back.
  • Case matters. replace("Cat", "dog") will not touch "cat". The match must be exact, including upper and lower case.
  • Thinking replace() only fixes the first match. By default it fixes them all. Use the count number if you want a limit.
note = "I love HTML and html"
# ❌ Avoid: assuming both get replaced
clean = note.replace("html", "CSS")
print(clean) # Only the lowercase one changes

Output

I love HTML and CSS

The uppercase "HTML" stayed because it did not match the lowercase "html" you searched for.

βœ… Best Practices

  • Always assign the result back: text = text.replace(old, new).
  • Use an empty string "" as the new value when you want to delete text.
  • Chain replaces for several small cleanups. But if the line gets long and hard to read, break it into separate steps.
  • If your match needs to ignore case or follow a pattern, plain replace() is not enough. That is the job of regular expressions, which is the next lesson.

🧩 What You’ve Learned

βœ… replace(old, new) returns a new string with the swap done.

βœ… Strings are immutable, so you must store the result, like text = text.replace(...).

βœ… By default replace() changes every match in the string.

βœ… A third count number limits how many swaps it makes.

βœ… You can chain replaces, and use "" as the new value to delete text.

βœ… It is the go-to tool for cleaning up data like phone numbers and dates.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does name.replace('a', 'b') do to the original name variable?

    Why: Strings are immutable, so replace() returns a new string and leaves the original untouched.

  2. 2

    How many matches does 'aaa'.replace('a', 'b') change?

    Why: By default replace() swaps every match it finds in the string.

  3. 3

    What does the third argument in replace(old, new, 2) control?

    Why: The optional count argument limits how many matches get replaced, here a maximum of two.

  4. 4

    How do you remove all commas from price = '1,000,000'?

    Why: Replacing with an empty string deletes the text, and you must store the result back in price.

πŸš€ What’s Next?

You can now swap exact text with confidence. But what if the thing you want to find follows a pattern instead of being fixed text, like any phone number or any email? For that you need a sharper tool.

Regular Expressions

Share & Connect