Text is everywhere. Learn to index, slice, transform and format strings, the most-used type in Python.
By the end of today you can
- Create strings with single, double and triple quotes
- Read characters with positive and negative indexes
- Cut out pieces of text with slicing
- Use common string methods like strip, split and replace
- Build readable output with f-strings
A string (str) is a sequence of characters: a name, a sentence, an email, a whole file. Today you'll learn to take strings apart and put them back together.
Making strings
Use single or double quotes; they mean the same thing. Triple quotes let a string span several lines.
Indexing: one character at a time
Every character has a position, called its index. Counting starts at 0. You can also count from the end with negative indexes.
Slicing: cut out a piece
A slice s[start:stop] takes characters from start up to, but not including, stop. Leave a side empty to go to the beginning or end.
| Slice | Meaning |
|---|---|
s[a:b] | From index a up to, not including, b |
s[:b] | The first b characters |
s[a:] | From a to the end |
s[::step] | Every step-th character; a step of -1 reverses |
Strings can't be changed (immutable)
You can't change a character inside a string. String methods always return a new string, so assign the result if you want to keep it.
Useful string methods
| Method | What it does |
|---|---|
upper(), lower(), title() | Change letter case |
strip() | Remove whitespace from both ends |
replace(old, new) | Replace every occurrence |
split(sep) | Break into a list of strings |
sep.join(list) | Join a list of strings with sep between |
startswith(x), endswith(x) | True or False |
find(x) | Index of the first match, or -1 |
f-strings: build text from values
Put an f before the quotes and write expressions inside curly braces. Add a format spec after a colon to control how values look.
Recap
- Strings are sequences of characters, written with
'…',"…"or"""…""". - Indexes start at
0; negative indexes count from the end. s[start:stop]slices fromstartup to, not including,stop.- Strings are immutable: methods return new strings.
- f-strings like
f"{price:.2f}"are the clearest way to format output.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
What does "python"[-1] return?
- 2
What does "python"[1:4] return?
- 3
You run name = "ada" and then name.upper(). What is name now?
- 4
What does "a,b,,c".split(",") return?
- 5
price = 4.5. Which f-string displays "Total: $4.50"?
Finished today's lesson?