Python
string manipulation
string.replace()
Python 3
programming tutorial

How to use string.replace in python 3.x

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

str.replace() is one of the simplest and most useful string methods in Python. It creates a new string by replacing occurrences of one substring with another, and understanding its immutability, optional count limit, and exact-match behavior helps avoid common text-processing bugs.

Basic Syntax

The method signature is:

python
new_text = text.replace(old, new, count)

count is optional. If you omit it, Python replaces all matching occurrences.

Example:

python
text = "apple apple banana"
print(text.replace("apple", "orange"))

Output:

text
orange orange banana

Replace Only the First Few Matches

Use count when you want controlled replacement:

python
text = "v1.2.3"
print(text.replace(".", "-", 1))

Output:

text
v1-2.3

This is useful when only the first few delimiters should change.

Strings Are Immutable

replace() does not modify the original string in place:

python
1name = "hello world"
2updated = name.replace("world", "python")
3
4print(name)
5print(updated)

Output:

text
hello world
hello python

You must assign the result if you want to keep it.

Replacement Is Case-Sensitive

replace() performs exact substring matching:

python
text = "Error error ERROR"
print(text.replace("error", "issue"))

Output:

text
Error issue ERROR

If you need case-insensitive replacement, use re.sub():

python
1import re
2
3text = "Error error ERROR"
4print(re.sub("error", "issue", text, flags=re.IGNORECASE))

That is a different tool because the matching rule is different.

Chaining Replacements

Chaining is common, but order matters:

python
text = "cat and dog"
result = text.replace("cat", "dog").replace("dog", "wolf")
print(result)

Output:

text
wolf and wolf

That may or may not be what you intended. If replacement rules overlap, use temporary placeholders or more deliberate logic.

Template-Like Replacement

For small fixed tokens, replace() can be convenient:

python
template = "Hello, [name]. Today is [day]."
message = template.replace("[name]", "Ava").replace("[day]", "Monday")
print(message)

For more complex templating, str.format() or f-strings are usually cleaner.

Replacing Many Fixed Tokens

If you have many literal replacements, a small loop is often easier to maintain than a very long chain:

python
1rules = {"cat": "feline", "dog": "canine"}
2text = "cat and dog"
3
4for old, new in rules.items():
5    text = text.replace(old, new)
6
7print(text)

This keeps the replacement rules in one place and makes later edits simpler.

Use the Right Tool for the Problem

replace() is best for literal substring changes. It is not a regex engine and not a parser. That means:

  • use replace() for exact literal substitutions
  • use re.sub() for pattern-based matching
  • use a parser when the input has real nested or formal structure

Choosing the right tool keeps the code readable and avoids fragile text hacks.

Strings Versus Bytes

str.replace() works on Python text strings. If your data is raw bytes from a file or socket, handle it as bytes explicitly or decode it first:

python
data = b"cat,dog"
print(data.replace(b"cat", b"fox"))

Mixing str and bytes carelessly is a common source of confusion in text-processing code.

Common Pitfalls

  • Expecting replace() to modify the original string in place.
  • Forgetting that matching is case-sensitive.
  • Chaining replacements without thinking about ordering effects.
  • Using replace() for pattern logic that actually needs regular expressions.
  • Replacing tokens in structured text without guarding against accidental partial matches.

Summary

  • 'str.replace() returns a new string with substring replacements.'
  • Omit count to replace all matches or pass it to limit replacements.
  • Strings are immutable, so assign the result.
  • Matching is literal and case-sensitive.
  • Use replace() for simple exact substitutions and move to regex only when the matching rules require it.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.