Python Strings · Lesson 26 of 149

Python String Immutability and Building Strings

What you will learn

  • What immutability means for strings, in practice
  • How to "change" a character by going through a list
  • Why building text with += in a loop can be slow, and the join fix
  • io.StringIO and string.Template for building text
  • Patterns for filtering and transforming characters

1. Strings never change

You met this in lesson 2.6: a str is immutable. Every operation that seems to change text actually builds a new string:

x = "abc"
y = x
x += "d"
print(x, y)
abcd abc

x += "d" made a new string "abcd" and moved x to it. y still points to the old "abc". For lists, the same line would have changed both names (lesson 2.7). Strings are the safe case.

Quick check: can you change the first letter of `"hello"` with `s[0] = "J"`?

No. It raises TypeError: 'str' object does not support item assignment. You need a new string.

2. Changing characters through a list

When you must change several characters, turn the string into a list of characters, change the list (lists are mutable), and join it back:

s = "hello"
chars = list(s)
chars[0] = "J"
chars[-1] = "y"
print(chars)
print("".join(chars))
['J', 'e', 'l', 'l', 'y']
Jelly

For a single change, slicing is simpler (lesson 4.2): "J" + s[1:].

3. Building text in a loop

A common task is building a long text from many pieces. The obvious way is += in a loop (loops are covered in chapter 6):

result = ""
for word in ["a", "b", "c"]:
    result += word + "-"
print(result)
print(result[:-1])
a-b-c-
a-b-c

This works, but each += may copy the whole string so far to make the new one, so for thousands of pieces it can get slow. The better habit is to collect the pieces in a list and join once:

parts = []
for word in ["a", "b", "c"]:
    parts.append(word)
print("-".join(parts))
a-b-c

You can also give join a generator directly, and use it to avoid the trailing dash:

print("-".join(word for word in ["a", "b", "c"]))
a-b-c

In a test that adds "x" twenty thousand times, the += loop was slower than join on the computer used for this lesson. Python sometimes optimises += for text, so the size of the difference varies from machine to machine and version to version. To measure your own code, use timeit (lesson 18.5). For a short text, either way is fine; write whichever is clearer.

4. Lines of text

To build text of several lines, join with "\n":

lines = ["a", "b", "c"]
print("\n".join(lines))
print("\n".join(f"{i}. {line}" for i, line in enumerate(lines, 1)))
a
b
c
1. a
2. b
3. c

enumerate(lines, 1) counts the lines starting at 1 (chapter 6).

5. StringIO: a text buffer

io.StringIO is an in-memory text file. You write into it as you would to a file, and read the whole text at the end:

import io

buf = io.StringIO()
buf.write("Hello")
buf.write(", ")
print("World", file=buf)
print(repr(buf.getvalue()))
buf.close()
'Hello, World\n'

It is useful when code expects a file object, or when you build output piece by piece. (Files are covered in chapter 15.)

6. string.Template

string.Template fills in names written as $name. It is simple, and it is a safer choice than .format() when the template comes from outside your program, for example from a file, because it only fills in plain names:

import string

t = string.Template("Hi $name, you owe $$$amount")
print(t.substitute(name="Rina", amount=5))
Hi Rina, you owe $5

$$ is a literal dollar sign. A missing name is an error with substitute, but is left as it is with safe_substitute:

print(t.safe_substitute(name="Rina"))
Hi Rina, you owe $$amount

(Here $$ became one $, and $amount was left alone, so you see $ followed by $amount.)

7. Filtering and transforming characters

A generator expression inside join lets you keep or change characters one by one (chapter 12 explains it):

word = "banana"
print("".join(c for c in word if c != "a"))
print("".join(c.upper() if i % 2 == 0 else c for i, c in enumerate(word)))
print("".join(chr(ord(c) + 1) for c in "HAL"))
bnn
BaNaNa
IBM
  • The first keeps every character that is not a.
  • The second capitalises every other letter.
  • The third moves each letter to the next one in the alphabet (ord gives the code number, chr turns it back into a character).

Other handy one-liners:

print("".join(sorted("hello")), "".join(reversed("hello")))
print("a-b_c d".translate(str.maketrans("-_ ", "   ")))
ehllo olleh
a b c d

Worked example: build a numbered shopping list

Build the text of a shopping list with each item on its own numbered line, using join.

items = ["rice", "salt", "oil"]
text = "\n".join(f"{n}. {item.title()}" for n, item in enumerate(items, 1))
print(text)
print(len(text.splitlines()))
1. Rice
2. Salt
3. Oil
3
Step What it does
enumerate(items, 1) pairs each item with a number from 1
f"{n}. {item.title()}" makes one line
"\n".join(...) joins the lines into one text
splitlines() splits it back, to count the lines

The items are made up for the example.

Common mistakes

  • Trying to assign to a character. Build a new string or use a list of characters.
  • Building a huge text with += in a loop without thinking. Collect pieces and join them.
  • Forgetting that join needs strings. Convert numbers with str(...).
  • Using .format() on a template that comes from outside your program. Prefer string.Template there.
  • Expecting += to change another name's string. Strings never change in place.

Key takeaways

  • Strings never change; operations make new strings.
  • To change characters, go through list(s) and "".join(...), or slice and rebuild.
  • For many pieces, build a list and join once instead of += in a loop; measure with timeit when it matters.
  • io.StringIO is an in-memory text file; string.Template fills $names safely.
  • join with a generator expression is a neat way to filter or transform characters.

Practice

1. Turn "python" into "Jython" in two ways.

Show answer

"J" + "python"[1:], or chars = list("python"), chars[0] = "J", "".join(chars).

2. Which is the better way to build one text from many pieces: += in a loop or join? Why?

Show answer

Usually join. Each += may copy the whole text so far, while join builds the result in one step.

3. Write a line that joins the numbers [1, 2, 3] into "1, 2, 3".

Show answer

", ".join(str(n) for n in [1, 2, 3]) or ", ".join(map(str, [1, 2, 3])).

4. Remove all vowels from "education" with join.

Show answer

"".join(c for c in "education" if c not in "aeiou") gives dctn.

5. What does string.Template("Hi $who").substitute() do, and how can you avoid that?

Show answer

It raises a KeyError, because who has no value. Use safe_substitute, which leaves $who unchanged.

6. Build the text "1-2-3-4" from the numbers 1 to 4.

Show answer

"-".join(str(n) for n in range(1, 5)).