Strings, slicing & f-strings
Strings are sequences of characters. In modern programming, you will slice substrings, sanitize user inputs, and format data with clean template strings on a daily basis.
- Access characters using zero-based and negative indexing.
- Extract sub-sequences with slice notation [start:stop:step].
- Format dynamic values cleanly with f-strings.
Indexing, slicing notation [start:stop:step], and f-strings.
Python strings are ordered sequences of Unicode characters. Slicing syntax is s[start:stop:step], where stop is exclusive. F-strings (f'...') evaluate expressions embedded in curly braces.
Zero-based indexing & slicing
Every character has an index starting at 0. Negative indices count backwards from the end (-1 is the last character). Slices take [start:stop], where stop is non-inclusive.
Modern f-strings vs concatenation
Prefixing a string with 'f' allows embedding any variable or expression directly inside curly braces `{}` without manual type conversion.
Memory Trace: String Slicing & Substring Allocation
Inspect character index offsets in memory as slicing extracts substrings.
| Variable | Value in Memory | Data Type |
|---|---|---|
| s | "Python" | str (length 6) |
| indices (0..5) | 'P','y','t','h','o','n' | auto |
Characters indexed at 0:P, 1:y, 2:t, 3:h, 4:o, 5:n.
s = "Python"🔧 IndexError in String Slicing
A student attempted to access the last character using len(word), causing an IndexError crash.
Predict The Output (2 Questions)
Your lightbulb moment
The key takeaway
Strings are 0-indexed sequences. Slices extract sub-ranges safely, and f-strings provide clean, readable string formatting.
Make it yours
Try slicing your name to print only the first 3 characters and the last character using negative indexing.
Try editing the code in the playground above in Python, JavaScript, Java, or C++, and use the step-by-step Dry-Run Table to inspect how variables mutate in memory. If you get stuck, click the 🤖 AI Doubt Solver button on your screen for instant explanations!