CodeMIRAI
0 XP

Indexing and slicing

2 min read 8 runnable examples Quiz included

Each character in a string has a position called an index. Python counts from 0.

Diagram
 P   y   t   h   o   n
 0   1   2   3   4   5
-6  -5  -4  -3  -2  -1

Indexing

Square brackets pick out one character:

Python
word = "Python"
print(word[0])    # first character
print(word[1])
print(word[5])    # last character

Negative indexes count from the end, so -1 is always the last character:

Python
word = "Python"
print(word[-1])
print(word[-2])

Going past the end is an error:

Python
word = "Python"
print(word[6])

Slicing

A slice takes a part of the string: text[start:stop]. It includes start and stops just before stop.

Python
word = "Python"
print(word[0:2])    # characters 0 and 1
print(word[2:5])    # characters 2, 3 and 4

Leave out start to begin at the start, or stop to go to the end:

Python
word = "Python"
print(word[:3])     # first three characters
print(word[3:])     # everything from index 3
print(word[-3:])    # last three characters
print(word[:])      # a copy of the whole string

Slices never cause an index error; they just stop at the end:

Python
print("Python"[2:100])

Steps

A third number sets the step:

Python
alphabet = "abcdefghij"
print(alphabet[::2])     # every second character
print(alphabet[1::2])    # every second, starting at index 1
print(alphabet[::-1])    # step -1 walks backwards: reversed!

text[::-1] is the classic one-line way to reverse a string, and a quick palindrome check:

Python
word = "level"
print(word == word[::-1])
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.