Lesson 4 of 34 · Fundamentals
Python Strings and f-Strings
Text is everywhere: names, messages, file contents, web pages. Python's str type comes with a rich toolbox for slicing, cleaning and searching text, and f-strings make it effortless to drop values into a message.
Creating strings
Wrap text in single or double quotes. Triple quotes let a string span several lines:
spell = "Fireball"
quote = 'Speak, friend, and enter.'
scroll = """Line one
Line two"""
Special characters are written with a backslash escape sequence: \n is a new line, \t a tab and \\ a backslash itself.
Joining, repeating and measuring
first = "Serpent"
print(first + " Hollow") # Serpent Hollow (concatenation)
print("ha" * 3) # hahaha (repetition)
print(len(first)) # 7 (number of characters)
Indexing and slicing
Each character has a position, starting at 0. Negative indexes count from the end:
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[0:3]) # Pyt (from index 0 up to, but not including, 3)
print(word[2:]) # thon
You'll learn slicing in depth with lists in Chapter 3 — it works the same way for strings.
String methods
Strings are immutable: they never change. Methods return a new string instead:
name = " ada lovelace "
print(name.strip()) # "ada lovelace" (remove surrounding whitespace)
print(name.strip().title()) # "Ada Lovelace"
print("hiss".upper()) # "HISS"
print("HISS".lower()) # "hiss"
print("hISS".capitalize()) # "Hiss" (first letter up, rest down)
print("a-b-c".replace("-", "+")) # "a+b+c"
print("dragon".startswith("dr")) # True
print("drag" in "dragon") # True (substring check)
There are also methods that test a string and return True or False: "42".isdigit(), "abc".isalpha(), "ABC".isupper(), "abc".islower() and "a1".isalnum() (letters or digits only).
f-strings: formatting made easy
Put an f before the opening quote, and any expression inside {curly braces} is evaluated and inserted into the text:
hero = "Ada"
level = 3
print(f"{hero} reached level {level}!") # Ada reached level 3!
print(f"Next level: {level + 1}") # Next level: 4
print(f"Shouting: {hero.upper()}") # Shouting: ADA
After a colon you can add a format spec to control how a value is displayed:
price = 4.5
print(f"{price:.2f}") # 4.50 (two decimal places)
print(f"{1234567:,}") # 1,234,567 (thousands separator)
print(f"[{'hi':>6}]") # [ hi] (right-align in 6 characters)
print(f"[{'hi':<6}]") # [hi ] (left-align)
:.2f rounds the value for display, so f"{0.999:.2f}" shows 1.00.
Common mistakes
- Forgetting the
f:"Level {level}"prints the braces literally. It must bef"Level {level}". - Adding text and numbers:
"Level " + 3raises aTypeError. Use an f-string orstr(3). - Expecting methods to change the string:
name.upper()on its own line does nothing useful. Store the result:name = name.upper(). - Indexing past the end:
"abc"[3]raisesIndexError— the last index islen(text) - 1.
Assignment
Write two functions that format text for the Hollow's notice board:
badge(name, level)returns"<Name> | Lvl <level>". Clean the name first: remove surrounding whitespace and capitalise it (first letter uppercase, the rest lowercase).price_tag(item, price)returns"<item>: $<price>"with the price always shown with exactly two decimal places.
badge("Ada", 3) # "Ada | Lvl 3"
badge(" grace ", 12) # "Grace | Lvl 12"
price_tag("Potion", 4.5) # "Potion: $4.50"
price_tag("Map", 0.999) # "Map: $1.00"Strings and formatting in other languages
- JavaScript Strings and Template Literals · JavaScript
- Go Strings and fmt.Sprintf Formatting · Go
- Java Strings and String Methods · Java
- C# Strings and String Interpolation · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .