Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.5 — Immutability, Interning and Building Strings Fast
Python · Example 4 of 4

StringIO as an in-memory file

A string can never be changed after it is created: every "change" builds a new string. Knowing this explains why s[0] = "J" fails, why joining pieces beats += in a loop, why you should compare strings with == and never is, and when io.StringIO is the right buffer.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Build the string "01234" once with += in a loop and once by collecting pieces in a list and joining them. Print both and whether they are equal.

02

Use io.StringIO and print(..., file=buffer) to collect three lines row 0, row 1, row 2 and then print the collected text.

03

Make two equal strings using "he" + "llo" and sys.intern("hel" + "lo") and show that comparing with == is True.

Explain it without notes

01

What does it mean that strings are immutable, and what happens when you write s = s + "!"?

02

Why is "".join(pieces) preferred over += in a loop?

03

Why is a == b the right way to compare strings, and what can a is b give?

04

When would you use io.StringIO?

StringIO as an in-memory file
Sign in to run this example in your browser.

Expected output

line 1
line 2
line 3
line 4
characters: 28