Skip to content

String Basics

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

Your turn

What does this print?

s = "ab"
t = s
s += "c"
print(s, t)

Mini quiz

1 / 3

Why can a repeated `s += ch` inside a loop cost O(n²)?