Strings
Python strings, the methods you'll actually use, and the f-string formatting tricks that make code readable.
What you'll learn
- ✓ Slicing and indexing — including negative indices
- ✓ The string methods every Python programmer knows by heart
- ✓ f-string formatting for numbers, dates, alignment, and debugging
Strings are sequences of characters. They’re immutable — every “modification” returns a new string.
Indexing and slicing
(click Run)The slice s[a:b:c] is start (inclusive), stop (exclusive), step. Negative
indices count from the right. This works on every Python sequence — lists,
tuples, bytes — so internalize it once.
The string methods you’ll use daily
" hi ".strip() # 'hi' — strip whitespace
"FOO".lower() # 'foo'
"foo bar".split() # ['foo', 'bar']
"foo,bar".split(",") # ['foo', 'bar']
",".join(["a", "b", "c"]) # 'a,b,c'
"hello".replace("l", "L") # 'heLLo'
"hello".startswith("he") # True
"hello".endswith("o") # True
"Hi {}".format("there") # 'Hi there' (old style)
f"Hi {name}" # f-string (preferred)
split() and join() are inverses you’ll combine constantly when cleaning
text.
f-strings — beyond {name}
f-strings are far more capable than just f"{name}". The format spec after
: lets you control width, precision, alignment, and more.
(click Run)f"{x=}" is a lifesaver during debugging — it auto-includes the variable
name and its value.
Raw strings — for paths and regex
path = r"C:\Users\Aarav\data.csv" # 'r' = treat backslashes literally
pattern = r"\d{4}-\d{2}-\d{2}" # regex for YYYY-MM-DD
Without the r, \n, \t, etc. would be interpreted as escape characters.
Always use raw strings for regex patterns.
Strings are immutable
s = "hello"
s[0] = "H" # TypeError — strings can't be modified in-place
s = "H" + s[1:] # ✓ creates a new string
This matters for performance. If you’re concatenating many strings in a
loop, every iteration creates a new object — slow. Prefer "".join(parts):
(click Run)Quick check
✦ Quick check
0/3 answeredNext
Strings live in lists, lists live in dicts. The next lesson covers lists — sorting, slicing, copying, and the methods that bite people most often.
Finished the lesson?
Mark it complete to track your progress and keep your streak alive. +20 XP