Lesson 37 min read

Strings & Formatting

Words are just arrays of characters wearing a trench coat

What Are Strings?

A string is a sequence of characters — letters, numbers, spaces, emojis, whatever. Under the hood, strings are stored much like a static array of characters. Think of it like a bracelet where each bead is one character. You can look at any bead by its position, but you can't change a bead once it's on the bracelet (strings are immutable).

You can create strings with single quotes 'hello', double quotes "hello", or triple quotes for multi-line text. Python doesn't care which quotes you use — just be consistent.

Creating Strings

# Different ways to create strings
greeting = "Hello, World!"
name = 'Alice'
# Triple quotes for multi-line strings
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you."""
print(poem)
# Strings with quotes inside
dialogue = "She said, 'Let's go!'"
print(dialogue)
# String length
print(len(greeting))
Output
Roses are red,
Violets are blue,
Python is awesome,
And so are you.
She said, 'Let's go!'
13

Indexing & Slicing

Every character in a string has an index (a position number). Python counts from 0, not 1. You can also count backwards using negative indices: -1 is the last character, -2 is second-to-last, and so on.

Slicing lets you grab a chunk of the string using [start:stop:step]. The stop index is NOT included — think of it like a fence: you stop before hitting it.

Indexing & Slicing

word = "PYTHON"
# P Y T H O N
# 0 1 2 3 4 5
# -6 -5 -4 -3 -2 -1
print(word[0]) # First character
print(word[-1]) # Last character
print(word[1:4]) # Characters 1, 2, 3 (not 4!)
print(word[:3]) # First 3 characters
print(word[3:]) # From index 3 to the end
print(word[::2]) # Every other character
print(word[::-1]) # Reversed!
Output
P
N
YTH
PYT
HON
PTO
NOHTYP

f-Strings: The Best Way to Format

f-strings (formatted string literals) are Python's cleanest way to mix variables into text. Just put an f before the opening quote and use curly braces {} around any expression you want to embed. You can even do math and call functions inside those braces!

f-Strings and Formatting

name = "Luna"
age = 12
height = 4.8333
# Basic f-string
print(f"Hi, I'm {name} and I'm {age} years old!")
# Math inside f-strings
print(f"Next year I'll be {age + 1}")
# Formatting numbers
print(f"Height: {height:.1f} feet") # 1 decimal place
print(f"Score: {42:05d}") # Pad with zeros
print(f"Price: ${19.9:.2f}") # 2 decimal places
# Expressions inside f-strings
items = ["sword", "shield", "potion"]
print(f"You have {len(items)} items")
Output
Hi, I'm Luna and I'm 12 years old!
Next year I'll be 13
Height: 4.8 feet
Score: 00042
Price: $19.90
You have 3 items

Handy String Methods

Strings come with a ton of built-in methods. Since strings are immutable, these methods always return a new string — the original stays unchanged.

Common String Methods

msg = " Hello, Python World! "
print(msg.strip()) # Remove leading/trailing spaces
print(msg.lower()) # All lowercase
print(msg.upper()) # ALL CAPS
print(msg.strip().replace("World", "Galaxy"))
# Splitting and joining
csv_line = "apple,banana,cherry"
fruits = csv_line.split(",") # Split into a list
print(fruits)
print(" & ".join(fruits)) # Join list back into a string
# Searching
story = "The cat sat on the mat"
print(story.count("at")) # How many times?
print(story.find("sat")) # Index where it starts
print(story.startswith("The")) # True or False?
print("cat" in story) # Membership check
Output
Hello, Python World!
  hello, python world!  
  HELLO, PYTHON WORLD!  
Hello, Python Galaxy!
['apple', 'banana', 'cherry']
apple & banana & cherry
3
8
True
True
Note: Strings are immutable — you can't change them in place. When you call msg.upper(), Python creates a brand new string. The original msg is untouched. It's like photocopying a letter and writing on the copy instead of the original.

Quick check

What does "PYTHON"[1:4] return?

Continue reading

Static ArraysData Structure
A row of numbered boxes — fast to grab, fixed in size
Trie (Prefix Tree)Data Structure
Insert, search, autocomplete
Operators & ExpressionsConditionals