Sub topic 1
Python String Indexing and Slicing
Prerequisites
You should know basic Python syntax, string literals, variables, print(), len(), and simple try/except blocks.
Strings as Ordered Sequences
A string is an immutable sequence of Unicode code points. A sequence stores items in a fixed order. A code point is a number representing a text character or part of a character.
word = "Python"
print(len(word))This prints 6. The string has six code points, stored in positions from left to right.
Reading One Character with a Zero-Based Index
Python uses zero-based indexing. The first item has index 0, the second has index 1, and so on.
s = "Python"
print(s[0])
print(s[2])
print(s[5])The output is:
P
t
nAn index is an integer inside square brackets. Indexing returns one code point as a one-character string.
| Expression | Result |
|---|---|
| `s[0]` | `"P"` |
| `s[3]` | `"h"` |
| `s[5]` | `"n"` |
Counting from the End with Negative Indexes
Negative indexes count from the right. The last item is -1, the item before it is -2, and so on.
s = "Python"
print(s[-1])
print(s[-6])Both expressions access the same positions as s[5] and s[0]. Negative indexes are useful when you need the end of a string without calculating its length.
>callout note >Positive indexes count from the beginning. Negative indexes count backward from the end. Both refer to the same ordered sequence. >```
When an Index Is Out of Range
A string of length six has valid indexes from 0 through 5, or from -6 through -1. Any other index raises IndexError.
s = "Python"
try:
print(s[6])
except IndexError as error:
print(type(error).__name__)The output is:
IndexErrorCheck the length or catch the exception when an index may be invalid.
Exercise
What does "Python"[-2] return, and why?
Show answer
It returns "o". Negative index -1 is "n", so -2 is the character before it.