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.
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:
count is optional. If you omit it, Python replaces all matching occurrences.
Example:
Output:
Replace Only the First Few Matches
Use count when you want controlled replacement:
Output:
This is useful when only the first few delimiters should change.
Strings Are Immutable
replace() does not modify the original string in place:
Output:
You must assign the result if you want to keep it.
Replacement Is Case-Sensitive
replace() performs exact substring matching:
Output:
If you need case-insensitive replacement, use re.sub():
That is a different tool because the matching rule is different.
Chaining Replacements
Chaining is common, but order matters:
Output:
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:
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:
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:
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
countto 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
- How to use subprocess command with pipes
- How to use TensorFlow in OOP style?
- How to use TensorFlow metrics in Keras
- How to use tensorflow on spyder?
- How to use tf.nn.embedding_lookup_sparse in TensorFlow?
- How to use tf.reset_default_graph
- How to use tf.reset_default_graph
- How to use tf.while_loop in tensorflow
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.