POST 1 of 5 MorningDSAConcept
Strings are immutable arrays of code points
Two facts about Python strings change how you write string code, and both trip up beginners.
Fact one — strings are immutable. Every operation that 'modifies' a string creates a new one. result += 'x' in a loop creates n new strings, each one bigger than the last, total work O(n²). For long strings or many concatenations, this is brutal.
The fix is one of the most-cited Python idioms. Build a list, join at the end:
parts = []
for x in items:
parts.append(transform(x))
result = ''.join(parts)
List append is O(1) amortised. join() does one pass over the list. Total: O(n). Identical output, much better complexity.
Fact two — strings are sequences of code points, not bytes. len('café') is 4, not 5. Iterating gives you four characters, even though the UTF-8 encoding is 5 bytes (because é is two bytes in UTF-8).
This is correct behaviour for almost every text operation you care about (word counts, slicing, indexing). It's confusing only when you're working at the byte level — networking, hashing, certain low-level file formats. For those cases, .encode('utf-8') gives you a bytes object, which IS indexed by byte.
Most of the bugs around code points happen at boundaries — Python strings vs bytes for files, strings vs bytes for network protocols, strings vs bytes for MD5 hashing. Always know which you're holding.
For everyday string work — slicing, searching, splitting, joining — Python's str does the right thing. Treat strings like immutable arrays of characters. Build with join(). Avoid += in loops. Reach for the byte representation only when you really mean bytes.#DSA#DataStructures#Algorithms#Python#100DaysOfCode#Strings