String Basics
Strings: lesson 1 of 11
Strings never change — every edit builds a brand-new one.
Lesson 1 of 11 · 4 min
String Basics
Step 1 of 9
Build STRING one character at a time, two ways. A Python string cannot be edited in place.
The Idea
A Python string is a fixed block of characters. Nothing edits it in place: slicing, .upper() and + each hand back a whole new string.
So s += ch in a loop can copy everything built so far, every time. An innocent-looking loop can quietly cost O(n²). CPython sometimes grows the string in place when nothing else refers to it, but the language does not promise that.
Real-World Example
A log shipper glues ten thousand lines into one payload with +=. Every line can re-copy the growing blob — megabytes of pointless memory traffic. Collecting the lines in a list and calling "".join() once at the end can turn seconds into milliseconds, with no other change.
The Code
s = "string"
# s[0] = "S" -> TypeError: strings are immutable
out = ""
for ch in s: # each += may copy the whole result again
out += ch.upper() # O(n²) across the loop, in general
print(out) # STRING
parts = []
for ch in s:
parts.append(ch.upper()) # appends are O(1)
print("".join(parts)) # STRING — copied once, O(n)Your turn
What does this print?
s = "ab"
t = s
s += "c"
print(s, t)Mini quiz
1 / 3