Because Python strings (str) are immutable, you cannot assign directly to an index (s[i] = "x" raises TypeError); instead, build a new string via slicing concatenation (s[:i] + new_char + s[i + 1:]) for single-position edits, or convert to a mutable list(s) (chars = list(s); chars[i] = "x"; "".join(chars)) when updating multiple indices in a loop.
Basic Example
text = "cat"
# 1. Recommended (single index replacement): String slicing concatenation
# Replace index 0 ('c') with 'b':
updated = text[:0] + "b" + text[1:]
print(updated) # Output: bat
# Replace index 1 ('a') with 'o':
updated_mid = text[:1] + "o" + text[2:]
print(updated_mid) # Output: cot
# 2. Recommended (multiple index replacements): Convert to a list of characters
chars = list("python")
chars[0] = "P"
chars[-1] = "N"
print("".join(chars)) # Output: PythoN
Key Details & Edge Cases
- Why
s[i] = "x"fails withTypeError:- Python
strobjects are immutable so they can be safely interned, hashed asdictkeys, and shared across threads without copying. Attemptingtext[0] = "b"immediately raisesTypeError: 'str' object does not support item assignment.
- Python
- Watch out for negative index
-1ins[:i] + ch + s[i + 1:]:- For
i = -1(the last character),i + 1equals0, sos[i + 1:]becomess[0:](the entire string!), producing"ca" + "r" + "cat"$\rightarrow$"carcat"instead of"car". - Either normalize negative indices first (
if i < 0: i += len(s)) or handle the last character withs[:-1] + new_char(or uselist(s), wherechars[-1] = "r"works natively).
- For
- Validate bounds before slicing (slicing silently clamps out-of-range indices):
- Unlike
list[i] = x(which raisesIndexErrorwheni >= len(s)), string slicing never raisesIndexError:"cat"[:10] + "x" + "cat"[11:]silently appends"x"to produce"catx". Check-len(s) <= i < len(s)if out-of-bounds indices should raise an error.
- Unlike
- Replacing with an empty string
""(deletion) or multi-character substring (insertion):- Slicing concatenation naturally handles deleting a character (
s[:i] + s[i + 1:]) or replacing 1 character with multiple characters (s[:1] + "oo" + s[2:]turns"cat"into"coot").
- Slicing concatenation naturally handles deleting a character (
- Avoid repeated
s = s[:i] + ch + s[i + 1:]inside a loop ($O(n^2)$ time):- Each string concatenation allocates and copies an entire new
strof length $n$. When modifying $k$ positions in a string of length $n$, convert tolist(s)once ($O(n)$), mutate indices in $O(1)$ each, and rejoin once with"".join(chars)($O(n)$ total).
- Each string concatenation allocates and copies an entire new
- ASCII byte-level in-place mutation (
bytearray):- For large ASCII-only buffers (such as DNA sequences or binary protocols) requiring millions of in-place single-byte updates,
buf = bytearray(b"ACGT")supports direct index assignment (buf[2] = ord("T")) in $O(1)$ without reallocating.
- For large ASCII-only buffers (such as DNA sequences or binary protocols) requiring millions of in-place single-byte updates,
Comparison of String Index Replacement Approaches in Python
| Method | Time Complexity | Handles Negative Indices (-1) Safely? |
Raises IndexError Out of Bounds? |
Best Used When |
|---|---|---|---|---|
s[:i] + new_ch + s[i + 1:] (Recommended for 1 edit) |
$O(n)$ (single allocation) | No (when i = -1, i + 1 == 0) |
No (silently clamps) | Replacing, deleting (""), or expanding a single known non-negative index in a string. |
chars = list(s); chars[i] = new_ch; "".join(chars) (Recommended for multiple edits) |
$O(n)$ total across $k$ edits | Yes (chars[-1] = "x") |
Yes | Updating multiple indices in a loop or when negative index safety and bounds checking matter. |
bytearray(s, "ascii") |
$O(1)$ per mutation | Yes | Yes | High-frequency in-place character/byte mutations on ASCII strings or binary buffers. |
s.replace(old, new, 1) |
$O(n)$ | N/A (value-based, not index-based) | N/A | Replacing the first occurrence of a known substring rather than a specific positional index. |
You must log in or register to comment.
