Skip to content
FollowtheDamnCode

Strings

Text in quotes — joining, repeating, and measuring it.

3 minute read

Big idea

A string (str) is text: any characters inside quotes. You can join strings, repeat them, and measure them.

The idea

first = "Ada"
last = 'Lovelace'          # single or double quotes — both fine

Joining strings with + is called concatenation:

Joining strings
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
print("ha" * 3)
print(len(full))
output
Ada Lovelace
hahaha
12

Run and edit it in the app.

  • + joins two strings into one.
  • * with a number repeats a string.
  • len(...) counts the characters — spaces count too.

Watch it

Text and numbers don't mix with +

+ needs both sides to be strings (or both numbers). Mixing them is an error:

Fix the bug: print "Level 5"
level = 5
print("Level " + level)
output
Level 5

Run and edit it in the app.

The error is TypeError: can only concatenate str (not "int") to str. Fix it with str(level), or by passing them to print separately: print("Level", level). In a few lessons, f-strings will make this effortless.

A number in quotes is text

Predict: maths or text?
print(2 + 3)
print("2" + "3")
print("2" * 3)
What does it print? Show the answer
5
23
222

Run and edit it in the app.

Long strings

Triple quotes let a string span several lines, keeping the line breaks:

A multi-line string
poem = """Roses are red,
Violets are blue,
Python is readable,
And now so are you."""
print(poem)
output
Roses are red,
Violets are blue,
Python is readable,
And now so are you.

Run and edit it in the app.

Strings can't be changed in place

A string is immutable: once made, its characters can't be edited. Operations like + build a new string. You'll see why this matters in the Strings module.

What is len("hi there")?

Think of it like

Letter beads on a string. + ties two strings of beads together; len counts the beads.

Key terms

  • String (str) — Text in quotes.
  • Concatenation — Joining strings with +.
  • len() — The number of characters in a string.
  • Immutable — Can't be changed after it's made.

Check yourself

What does "ab" + "cd" give?

What does "Level " + 5 do?

What is len("cat")?