PythonPython StringsPython substring replacement
How do you replace a substring in a string?
Question 72 of 88 · Updated
On this page
- 1. Basic syntax and replacement count
- 2. Non-overlapping matches and one-pass semantics
- 3. Deletion and empty search strings
- 4. Zero, negative and keyword counts
- 5. Unicode matching and normalization
- 6. Literal replacement versus regular expressions
- 7. Practical example: bound the output size
- 8. Multiple substitutions: sequential versus simultaneous
- 9. Failure modes and complexity
- 10. Common mistakes and choosing an interface
- Interview-ready answer
- Official references
Use text.replace(old, new) to replace every non-overlapping occurrence of a literal substring with another string. To replace only the first few occurrences, supply a third argument: text.replace(old, new, count).
The operation returns a string result and leaves the original immutable string unchanged. It performs literal, case-sensitive matching, not regular-expression matching.
1. Basic syntax and replacement count#
PYTHONtext = 'red red blue' print(text.replace('red', 'green')) print(text.replace('red', 'green', 1)) print(text)
Output:
green green blue
green red blue
red red blueThe first argument identifies the exact text to match. The second identifies the replacement text. The optional count limits the number of replacements, beginning with the earliest matching occurrence.
| Argument | Meaning |
|---|---|
| old | Literal substring to search for |
| new | Text to insert in place of each selected match |
| count | Maximum number of replacements; a negative value means unlimited |
If old does not occur, the resulting text is equal to the original. An implementation may reuse an existing immutable object when appropriate; do not use object identity to determine whether a substitution took place.
To retain the transformed value, assign the result to a name or pass it to the next processing step. Calling replace and ignoring its return value does not edit the input.
2. Non-overlapping matches and one-pass semantics#
PYTHONprint('aaaaa'.replace('aa', 'X')) print('a'.replace('a', 'aa')) print('Red red'.replace('red', 'blue'))
Output:
XXa
aa
Red blueThe first input contains overlapping potential occurrences of aa. Python selects non-overlapping matches from the left: positions 0–1 and 2–3. The last a remains unmatched.
The inserted text is not searched again within the same replace call. Therefore replacing a with aa in a one-character string terminates with two characters, rather than repeatedly expanding the inserted value.
The third example demonstrates case sensitivity. Red is not the same literal substring as red.
If the desired operation involves overlapping matches, define precisely which original positions to consume and how to resolve conflicts before implementing it. Native replace is not an overlapping rewrite engine.
3. Deletion and empty search strings#
PYTHONprint('abc'.replace('', '-')) print('abc'.replace('', '-', 2)) print(repr(''.replace('', '-'))) print('a-b-c'.replace('-', ''))
Output:
-a-b-c-
-a-bc
'-'
abcAn empty replacement string deletes each selected occurrence of old. An empty search string has a different meaning: it matches the boundaries before the first code point, between consecutive code points and after the last code point.
A string containing n code points has n + 1 such boundaries. Even an empty string has one boundary.
With a limit of two, the empty search string matches only the first two boundaries in abc, producing -a-bc.
Unlike split(''), which raises ValueError, replace('', new) is a valid operation. This distinction matters when the search text comes from an input field. An accidentally empty search value can insert replacement text throughout a document.
4. Zero, negative and keyword counts#
PYTHONprint('a:a:a'.replace('a', 'b', 0)) print('a:a:a'.replace('a', 'b', -2)) print('a:a:a'.replace('a', 'b', count=2))
Output:
a:a:a
b:b:b
b:b:aA zero count performs no replacements. Any supported negative integer count requests unlimited replacement. Positive counts select at most that many non-overlapping matches from the left.
Python 3.13 added support for passing count as a keyword argument. On older Python versions, use the positional third argument for compatibility. The old and new arguments remain positional-only in Python 3.13.
The count must support the integer-index protocol; a float such as 1.5 does not satisfy the contract. Ordinary strings must be supplied for old and new.
If you need to replace the last occurrence rather than the first, a different selection strategy is required, such as locating the final occurrence and composing the surrounding slices. A negative count does not mean replacement from the right.
5. Unicode matching and normalization#
PYTHONfrom unicodedata import normalize text = 'cafe\u0301' print(text.replace('é', 'e') == text) print(normalize('NFC', text).replace('é', 'e'))
Output:
True
cafeThe original string ends in a decomposed sequence consisting of e followed by a combining acute accent. The search string é is a precomposed Unicode code point, so literal replacement finds no match.
Normalization to NFC first makes the representations match in this example. That normalization is a separate transformation and may also change other text in the input. Do not normalize blindly when exact code-point sequences must be preserved.
Likewise, replacing part of a multi-code-point grapheme cluster can change how a human-perceived character is displayed.
For case-insensitive matching, do not simply casefold the entire original string and then return a replacement of that folded text if original casing matters. Folding may change text lengths and the positions of matches. Use a matching strategy appropriate to the required Unicode semantics.
6. Literal replacement versus regular expressions#
PYTHONimport re text = 'cat scatter CAT' print(text.replace('cat', 'dog')) print(re.sub(r'\bcat\b', 'dog', text, flags=re.IGNORECASE))
Output:
dog sdogter CAT
dog scatter dogThe literal replace method matches cat wherever the exact sequence occurs, including inside scatter. The regular-expression example uses word boundaries and case-insensitive matching, so it replaces cat and CAT as standalone matches.
The regular expression's word-boundary rules are defined by Python's regex engine; they are not a complete natural-language tokenizer. For languages or formats with specialized boundaries, use a suitable parser or segmentation policy.
Choose replace when the search text is literal. It does not interpret characters such as periods, brackets or asterisks as patterns. Use re.sub when pattern matching, captures or a callable replacement is needed.
If an external literal must be used inside a regex pattern, escape it appropriately, for example with re.escape. A regex replacement string has its own escape and backreference semantics; a callable returning the intended literal text avoids interpreting those replacement escapes. Detailed re.sub behavior belongs to the dedicated regular-expression lesson.
7. Practical example: bound the output size#
PYTHONdef bounded_replace(text, old, new, limit=1000): if not old: raise ValueError('empty search string') matches = text.count(old) if len(text) + matches * (len(new) - len(old)) > limit: raise ValueError('output too long') return text.replace(old, new) print(bounded_replace('a-a', 'a', 'xy')) try: bounded_replace('aaa', 'a', 'xxxx', 10) except ValueError as exc: print(exc)
Output:
xy-xy
output too longFor an input of length n, a nonempty search string of length a, a replacement of length b and k selected matches, the output length is:
L = n + k * (b - a)The count method counts non-overlapping occurrences, matching the unlimited literal replacement model. The helper calculates the expected output length before allocating the result. It rejects an empty search string as a deliberate application policy, not because Python forbids it.
The function assumes ordinary str arguments and a trusted nonnegative integer limit. A public interface should validate those types and separately bound input length, because the preliminary count itself requires processing the input. This limit measures Unicode code points, not encoded bytes or actual memory consumption.
A limited-count variant would use the smaller of the available match count and the permitted nonnegative replacement count. For an empty search string, the available number of matches would instead be n + 1.
8. Multiple substitutions: sequential versus simultaneous#
PYTHONprint('a b c'.replace(' ', '_')) print('abc'.translate(str.maketrans({'a': 'b', 'b': 'c'}))) print('abc'.replace('a', 'b').replace('b', 'c'))
Output:
a_b_c
bcc
cccChaining replace calls is sequential: every later call sees the complete result of the previous call. In the last example, a becomes b in the first operation, and that newly inserted b becomes c in the second operation.
The translate method instead applies a character mapping to each original code point. The original a maps to b, the original b maps to c, and the original c remains unchanged.
Translate is appropriate for many independent single-code-point mappings, including mappings to multi-code-point strings or deletion. It does not provide general simultaneous matching of multi-character substrings.
For multiple substring rules that may conflict, specify precedence, overlap behavior and whether inserted text may be rewritten. A sequence of replace calls implements one particular policy, not a universally equivalent simultaneous substitution.
9. Failure modes and complexity#
| Operation | Expected behavior |
|---|---|
'abc'.replace(1,'x') | TypeError: invalid search type |
'abc'.replace('a',None) | TypeError: invalid replacement type |
'abc'.replace('a','b',1.5) | TypeError: invalid count type |
'abc'.replace('z','x') | 'abc' |
'abc'.replace('a','x',0) | 'abc' |
Native replacement does not raise an exception merely because the requested substring is absent. If an application requires a match, check that requirement explicitly.
Let n denote input length and L denote output length. For ordinary CPython strings and a fixed nonempty search pattern of bounded length, a conventional worst-case time model is O(n + L), including finding matches and constructing the result. For arbitrary pattern lengths, the substring-search algorithm and implementation-specific special cases matter. Python's language specification does not guarantee a particular algorithm.
A materialized result typically requires O(L) storage under a bounded-width Unicode representation model. The original input may remain alive while the result is constructed. Chaining many replacements can repeatedly scan and copy text, so include the cost of intermediate results when evaluating a transformation pipeline.
The bounded helper additionally performs a count pass. This is a deliberate trade-off for rejecting excessive output before allocation.
10. Common mistakes and choosing an interface#
| Mistake or requirement | Correct approach |
|---|---|
| Expecting the original string to change | Use the returned value |
| Replacing only one occurrence | Supply count=1, or positional 1 on older versions |
| Treating old as a regex pattern | Use re.sub for actual pattern matching |
| Accidentally accepting empty old | Validate the search value if empty matches are not intended |
| Removing an exact prefix or suffix | Use removeprefix or removesuffix |
| Performing independent character mappings | Consider translate and maketrans |
| Expecting replacement to sanitize SQL or HTML | Use parameterization or context-specific escaping |
Literal substitutions do not understand quoting, grammar, identifiers or security boundaries. For example, globally replacing text inside JSON or source code may also alter escaped strings or unrelated fields. Parse structured input, update the intended values, and serialize using the appropriate interface.
For large text streams, independently replacing each arbitrary chunk can miss matches spanning chunk boundaries. A streaming replacement implementation must preserve enough boundary context and maintain the same non-overlap and count policy.
Interview-ready answer#
Python replaces literal substrings with str.replace(old, new, count). It returns a string without changing the original, matches case-sensitively and replaces non-overlapping occurrences from left to right. A missing or negative count means unlimited replacements, zero means none, and a positive count limits the number of substitutions. An empty replacement deletes matches; an empty search string matches code-point boundaries. Newly inserted text is not rescanned within one call. Use re.sub for pattern-based replacements and translate for independent character mappings. Consider Unicode normalization, output size and the actual text format when designing production transformations.
Official references#
- Python Standard Library — str.replace
- Python Standard Library — str.count
- Python Standard Library — str.translate
- Python Standard Library — str.maketrans
- Python Standard Library — re.sub
- Python Standard Library — unicodedata.normalize
- Python Unicode HOWTO
Verification note: Eight runnable Python example groups matched their documented outputs in separate namespaces on CPython 3.13.5. Three independent expected TypeError tests passed. Across 500 seeded randomized inputs, including empty patterns, Unicode characters and negative or bounded counts, 1,000 assertions compared native replacement with an independently implemented boundary/non-overlapping scan and verified the output-length formula. Both triple-backtick fenced Mermaid diagrams were manually reviewed; the local Mermaid CLI was unavailable, and parser-level validation and public-site rendering were not performed. Older Python versions were not separately executed. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.
References
- 1.Python Standard Library — str.replacedocs.python.org
- 2.Python Standard Library — re.subdocs.python.org
- 3.Python Standard Library — unicodedata.normalizedocs.python.org
- 4.Python Unicode HOWTOdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design