12. Strings
Strings are the values you print most. Python has a rich set of tools for them built directly onto string objects: joining, measuring, changing case, repeating, and formatting numbers into them. This chapter covers the ones you use daily.
Joining strings with
+ and f-strings
You can join two strings with + (the
concatenation operator). It returns one new string with
the second stuck onto the end of the first:
first = "Hello, "
second = "world!"
print(first + second) # Hello, world!The original variables are untouched — + builds a new
string.
Python's + does not automatically convert numbers to
strings. Adding a number to a string is an error:
level = 7
# print("Level " + level) # TypeError: can only concatenate str to strThe fix is to wrap the number in str(), or use an
f-string, which is the preferred Python approach:
level = 7
print("Level " + str(level) + " complete") # Level 7 complete
print(f"Level {level} complete") # Level 7 completeAn f-string starts with the letter f before the opening
quote. Any expression inside {} is evaluated and inserted
into the string. F-strings handle numbers, booleans, and any other type
automatically.
Length with len
The len() function returns a string's length in
characters:
print(len("hello")) # 5
print(len("")) # 0
greeting = "Welcome"
print(len(greeting)) # 7Use len() whenever you need a string's length — for
centring text, checking input length, or building borders.
Open exercises/12/01-length.py. Add a line that prints
the length of your own name.
Changing case
String methods live directly on string objects, called with a dot.
Two simple ones are .upper() and .lower().
Both return a new string and leave the original
alone:
name = "Keiko"
print(name.upper()) # KEIKO
print(name.lower()) # keiko
print(name) # Keiko (still the original)Repeating a string
Multiplying a string by an integer with * repeats it
that many times:
print("-" * 20) # --------------------
print("ab" * 3) # ababab
print("=" * 4 + " TITLE " + "=" * 4) # ==== TITLE ====It is the right tool for drawing borders or padding text.
Formatting with f-strings
When you need numbers or text plugged into specific spots, f-strings
are the standard approach. Place any expression inside
{}:
name = "Keiko"
level = 7
hp = 95
print(f"{name} (Lv {level}) HP {hp}")
# Keiko (Lv 7) HP 95For control over decimal places and number formatting, add a format specification after a colon inside the braces:
| Format spec | What it does | Example output |
|---|---|---|
{x} |
default conversion | Keiko or 7 |
{x:.2f} |
float with two decimal places | 3.14 |
{x:d} |
integer | 7 |
{x:10} |
pad to width 10 | Keiko |
price = 3.14159
print(f"Price: {price:.2f}") # Price: 3.14Open exercises/12/02-format.py. Change the f-string so
the output reads Keiko has 95 HP at level 7.
Escape sequences
Some characters are awkward in a string because they collide with
Python's punctuation. The fix is an escape sequence — a
backslash \ followed by a letter, which Python replaces
with the special character:
| Sequence | What it becomes |
|---|---|
\n |
a newline (move to next line) |
\t |
a tab |
\" |
a literal double quote |
\' |
a literal single quote |
\\ |
a literal backslash |
Example:
print("Line 1\nLine 2\nLine 3")
# Line 1
# Line 2
# Line 3
print("Name\tLevel\tHP")
# Name Level HP
print("She said \"hi\" and waved.")
# She said "hi" and waved.Multi-line strings
When a string spans many lines with lots of quotes, escape sequences
get noisy. Python offers triple-quoted strings: """ to open
and """ to close (or ''' and
'''). Anything between them is the string, including
newlines and quotes:
poem = """
Roses are red,
Violets are blue,
"Pick a number,"
said the program to you.
"""
print(poem)Once created, triple-quoted strings are just regular strings — a friendlier way to write them.
Homework
Problem 1 — Loud and quiet
Open exercises/12/homework/01-loud-and-quiet.py. A
starter variable holds your name. Print it three times: as-is, in upper
case, then in lower case.
Problem 2 — Stat line
Open exercises/12/homework/02-stat-line.py. Three
variables are declared at the top: a string name, an integer level, an
integer hp. Using an f-string, print one line in this exact shape:
Keiko Lv 7 HP 95
The labels (Lv, HP) and the spacing between
fields can be literal spaces inside the f-string.
Problem 3 — One-line three-line poem
Open exercises/12/homework/03-three-line-poem.py. Print
a three line poem using exactly one print
call. The line breaks must come from \n inside the string.
Add a # comment after the print call explaining why one
print can produce three lines.
Challenge — Title block
Open exercises/12/homework/04-title-block.py. A variable
holds a title (any string you like). Print a block like this, where the
top and bottom dash rows match the title's length plus two dashes on
each side:
----- INVENTORY -----
Inside text goes here
----- INVENTORY -----
Use "-" * n and len() to size the borders
without counting by hand. Changing the title should change the border
length automatically.
Stuck or finished? Open the homework solutions page.