Strings & Formatting
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
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
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
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.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
Continue reading