Beginner guide to understanding Python’s slice object.
If you’re unsure about how Python indexes and slices strings, this article is for you! First, let’s explore indexes. (Indices for the grammatically correct!).
This is a companion article to my beginner series:
The first element in a sequence has the index 0. Not 1. This is often a source of confusion!
Although the first character has the index 0, and the last character has index 11, there are in fact 12 characters in this string.
The character at index position 6 is ‘W’
.
Going forwards from 0, W
is at index position 6.
Going backwards from -1, W
is at index position -6.
The negative index begins at -1
, not zero. Why? Zero is already used for the first character in the forward index!
Python has a very handy enumerate()
method. It gives us each element of the character sequence, and the index starting at 0.
This prints out the following in my terminal:
[(0, ‘H’), (1, ‘e’), (2, ‘l’), (3, ‘l’), (4, ‘o’), (5, ‘ ‘), (6, ‘W’), (7, ‘o’), (8, ‘r’), (9, ‘l’), (10, ‘d’), (11, ‘!’)]
This corresponds nicely to the first image, above.
The character at index position 12 is… not there at all!
Trying to access an index position which is outside of the bounds raises an error:
IndexError: string index out of range
#beginner #learn-to-code #programming #python