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:

Python Uses Zero-Based Indexes

The first element in a sequence has the index 0. Not 1. This is often a source of confusion!

Image for post

Although the first character has the index 0, and the last character has index 11, there are in fact 12 characters in this string.

Access an Index using Square Brackets

Image for post

The character at index position 6 is ‘W’.

Using Negative Index Numbers

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!

Enumerating The Sequence of Characters

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.

Python’s IndexError

The character at index position 12 is… not there at all!

Image for post

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

A Visual Guide to Python Slices and Indexes
2.55 GEEK