Algorithmsstring modification
String Modification (immutable str, list+join)
TT
Testlaa Team
May 14, 2026•1 min read
Modifying strings in Python means producing a new str—slicing, replace, list-of-chars mutation then join, or bytearray for bytes. True in-place character edits do not exist for str.
Why this shows up in the real world
Immutable configs are updated by cloning and swapping references. Game grids stored as strings of tiles are rebuilt each tick from rules.
Core idea (explained for students)
Common pattern: chars = list(s); chars[i] = ch; out = ''.join(chars). For many replacements, consider building a list of segments and joining once.
Try this in Python
def swap_edges(s: str) -> str:
if len(s) < 2:
return s
return s[-1] + s[1:-1] + s[0]
print(swap_edges("abcde"))
Common mistakes
s[i] = xsyntax error—strings are immutable.- Chained
replaceorder changing unintended substrings.
Key takeaways
- For frequent updates,
listorarray('u')historically; oftenio.StringIOor list buffers for builders. - Snapshot before destructive transforms for easier tests.
Tags:
StringsPythonStudents
