Phase 1 · FoundationsModule 3~36 min read

Strings & Formatting

Master Python's powerful text type: slicing, methods, and clean formatting with f-strings.

What you'll learn

Text is the most common data you'll ever handle — names, messages, files, web pages. Python's str type is powerful and pleasant to work with. This module makes you fluent with strings and Python's wonderful f-strings.

By the end you'll be able to:

  • Create strings with single, double, and triple quotes
  • Index and slice strings (including reversing them!)
  • Transform text with the essential string methods
  • Format output cleanly with f-strings
  • Use escape sequences and raw strings

Creating strings

A string is text wrapped in quotes. Single (') and double (") quotes work identically — pick whichever avoids escaping. Triple quotes create multiline strings:

strings.py
single = 'Hello'
double = "World"
multi = """This string
spans multiple lines."""

print(single, double)
print(multi)

Strings are immutable

Once created, a string can never be changed in place — name[0] = "S" is an error. Every "modification" actually returns a new string, which is why you write name = name.capitalize().
immutable.py
name = "sara"

# name[0] = "S"   # TypeError — strings can't be changed in place

name = name.capitalize()   # methods return a NEW string
print(name)                # Sara

Indexing & slicing

Each character has a position (an index), starting at 0. Python also allows negative indexes counting from the end, and slicing to grab a range with [start:stop:step]:

How string indexes work
0
P
-6
1
y
-5
2
t
-4
3
h
-3
4
o
-2
5
n
-1

Positive indexes count from the start (0…), negative from the end (-1 is the last character). word[1:4] takes indexes 1, 2, 3 — the stop is excluded.

slicing.py
word = "Python"

print(word[0])      # P      first character
print(word[-1])     # n      last character
print(word[0:3])    # Pyt    indexes 0, 1, 2
print(word[2:])     # thon   from 2 to the end
print(word[::-1])   # nohtyP reversed!
print(len(word))    # 6      length

Tip

The slice trick word[::-1] reverses any string (or list) — a step of -1 walks backwards. Slicing is one of Python's most-loved features; you'll use it constantly.

Essential string methods

Strings come loaded with useful methods. Remember: because strings are immutable, these all return a new value rather than changing the original:

MethodWhat it does
.strip()remove surrounding whitespace
.lower() / .upper()change case
.split(sep)break into a list around sep
.join(list)join a list into a string
.replace(a, b)replace every a with b
.startswith(x) / .endswith(x)test the start/end
.find(x) / .count(x)locate / count occurrences
methods.py
text = "  Hello, Python  "

print(text.strip())               # "Hello, Python"
print("PYTHON".lower())           # python
print("a,b,c".split(","))         # ['a', 'b', 'c']
print("-".join(["a", "b", "c"]))  # a-b-c
print("Python".replace("P", "J")) # Jython
print("banana".count("a"))        # 3

f-strings: the best way to format

To build text from values, use an f-string — put an f before the quote and drop variables (or any expression) inside { }. It's readable, fast, and the modern standard:

Anatomy of an f-string
f"Hi {name}, you are {age + 1} next year"

The f prefix

Marks this as a formatted string.

{ } placeholders

Slot a variable's value straight into the text.

Any expression

Even maths and method calls work inside the braces.

fstrings.py
name = "Sara"
age = 25
pi = 3.14159

print(f"{name} is {age} years old")
print(f"Next year: {age + 1}")     # expressions work
print(f"Pi is {pi:.2f}")           # format: 2 decimals
print(f"{name.upper()} rocks")     # method calls work too

Format specifiers

After a colon inside the braces you can control formatting: :.2f shows 2 decimals, :, adds thousands separators, :>10 right-aligns in 10 spaces. You'll dig deeper into these in the next module.

Escape sequences & raw strings

Some characters can't be typed directly — a newline, a tab, or a quote that would end the string. Escape them with a backslash. And when you want backslashes taken literally (file paths, regex), prefix the string with r for a raw string:

EscapeResult
\nnew line
\ttab
\"a double quote
\\a backslash
escapes.py
print("Line 1\nLine 2")      # \n starts a new line
print("Col1\tCol2")          # \t inserts a tab
print("She said \"hi\"")    # \" is an escaped quote
print(r"raw: \n stays \n")  # r"..." = raw string, no escapes

Recap & quick check

Key takeaways

  • Strings use single, double, or triple (multiline) quotes, and are immutable.
  • Index from 0 (or from the end with negatives); slice with [start:stop:step] — word[::-1] reverses.
  • String methods (strip, split, join, replace…) return new strings.
  • f-strings — f"...{value}..." — are the modern, readable way to build text, and run any expression.
  • Use \n, \t etc. for escapes, and r"..." for raw strings where backslashes are literal.

Quick check

1. What does word[-1] give you?

2. How do you reverse a string with slicing?

3. Can you change a character in a string in place?

4. Which is the modern, recommended way to format text?

5. What does r"..." (a raw string) do?

Great — text holds no mystery now. Next up: Module 4 — Input, Output & Program Structure.