Module lessons (2/4)
Slicing and indexing
Positive and negative indices, [start:stop:step] slices, string reversal, and substrings.
What you'll learn in this lesson
- Read characters via positive (
0..n-1) and negative (-1..-n) indices. - Master
[start:stop:step]slicing knowing thatstopis always excluded and out-of-range slicing is tolerant. - Reverse sequences with
[::-1]and extract prefixes, suffixes and delimited fields without errors.
Overview
In Python, strings support indexing and slicing with the same universal syntax as lists and tuples ([start:stop:step]). Thoroughly knowing the inclusive/exclusive boundaries of this mechanism means being able to cut, extract and reverse text in just a few characters.
Imagine positive indices as labels before each character (0, 1, 2, ...): the slice s[a:b] includes from a inclusive up to b excluding, so its length is exactly b - a and two adjacent slices s[:k] + s[k:] always reconstruct the entire string without overlaps!
Sections covered in this lesson
- 1The mental model: indices positioned between characters
- 2Safe slicing, negative step and position search
- 3Quick check
- 4Test yourself
Unlock "Slicing and indexing" and the full Python Course curriculum
Positive and negative indices, [start:stop:step] slices, string reversal, and substrings.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.