Sub topic 11
Indexing and Slicing Strings
This chapter assumes you can run Python code, call print(), and know that a string (str) is a sequence of text characters written in quotes. You should also know that a name refers to an object. Here you will learn how to pull single characters and pieces out of a string, and how to avoid the errors that come with it.
Strings as ordered sequences
A string is a sequence: an ordered collection of characters. Each character has a position, called an index. Python counts positions from 0, so the first character is at index 0.
s = "Python"
print(s[0])
print(s[5])
print(len(s))This prints P, n, and 6. The string has 6 characters, and the valid indexes run from 0 to 5. The last valid index is always len(s) - 1.
Indexing returns a new string of length 1. Python has no separate character type, so s[0] is a str, the same type as s.
Negative indexes
Negative indexes count from the end. Index -1 is the last character, -2 is the one before it, and so on.
s = "Python"
print(s[-1])
print(s[-2])
print(s[len(s) - 1] == s[-1])This prints n, o, and True. For a string of length n, the index -k means the same position as n - k. Negative indexes are the clearest way to get the last character, because you don't need to compute the length.
The table shows both numbering schemes for "Python".
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
Index errors
An index outside the valid range raises IndexError. This is one of the most common mistakes, and it usually comes from an off-by-one error.
s = "Python"
try:
print(s[6])
except IndexError as e:
print("IndexError:", e)
try:
print(""[0])
except IndexError as e:
print("IndexError:", e)Both lookups fail. Index 6 is past the end of a 6-character string. The empty string has no valid index at all, so code like text[0] fails on empty input. If the string might be empty, check it first (if text:) or use a slice, which never raises (see below).
Slicing
A slice extracts a piece of a string. The syntax is s[start:stop]. It includes the character at start and stops before the character at stop.
s = "Python"
print(s[1:4])
print(s[0:2])
print(s[:3])
print(s[3:])
print(s[:])This prints yth, Py, Pyt, hon, and Python. Leaving out start means "from the beginning". Leaving out stop means "to the end".
The "stop is excluded" rule has two useful consequences:
- The length of
s[a:b]isb - a(when both are in range). s[:n] + s[n:]always equalss, so you can split a string at any point without overlap or gaps.
Think of the indexes as pointing to the gaps between characters instead of the characters themselves:
The slice s[1:4] starts at boundary 1 and ends at boundary 4, so it contains y, t, and h.
Negative and out-of-range bounds
Slice bounds can be negative, and they follow the same counting rules as indexes.
s = "Python"
print(s[-3:])
print(s[:-1])
print(s[-4:-1])
print(s[2:100])
print(s[10:20] == "")This prints hon, Pytho, tho, thon, and True. Unlike plain indexing, slicing never raises IndexError. Python clamps bounds that are too large to the end of the string. A slice that selects nothing returns an empty string. This makes slices safe on short or empty input: text[:1] is "" for an empty string, whereas text[0] raises an error.
If start is at or after stop (with the default positive step), the result is also empty.
s = "Python"
print(repr(s[4:2]))This prints ''.
The step
A slice can take a third value, the step: s[start:stop:step]. The step is how far to move between selected characters. It defaults to 1.
s = "Python"
print(s[::2])
print(s[1::2])
print(s[::-1])
print(s[4:1:-1])This prints Pto, yhn, nohtyP, and oht. A step of 2 takes every second character. A step of -1 walks backward, so s[::-1] is the standard idiom for reversing a string.
With a negative step, the defaults change. start defaults to the last character and stop defaults to "before the first character". In s[4:1:-1] you start at index 4 (o) and move left, stopping before index 1, so you get o, h, t. A step of 0 raises ValueError.
A common mistake is writing bounds in the wrong order for a negative step. s[1:4:-1] is empty, because you cannot walk backward from 1 to reach 4.
s = "Python"
print(repr(s[1:4:-1]))
try:
s[::0]
except ValueError as e:
print("ValueError:", e)The first line prints ''. The second prints ValueError: slice step cannot be zero.
Slices create new strings
Every index and slice returns a new string. It never changes the original. The original is also not "shared" in a way you can modify, because strings are immutable, a topic covered in the next chapter. For now, note what happens when you try to assign into a string:
s = "Python"
try:
s[0] = "J"
except TypeError as e:
print("TypeError:", e)
print("J" + s[1:])
print(s)The assignment raises TypeError because a string does not support item assignment. To "change" a character, build a new string from slices, as in "J" + s[1:]. The name s still refers to the original "Python".
Slice objects and reuse
The s[a:b:c] notation is shorthand for creating a slice object. You can build one yourself and reuse it. This is helpful when you cut the same fields from many fixed-width strings.
first_three = slice(0, 3)
last_two = slice(-2, None)
for word in ["alpha", "beta", "gamma"]:
print(word[first_three], word[last_two])This prints alp ha, bet ta, and gam ma. Use None in place of an omitted bound.
Practical patterns
Some patterns come up often:
filename = "report_2026.csv"
print(filename[-4:])
print(filename[:-4])
print(filename[7:11])
code = "A1B2C3"
print(code[::2])
print(code[1::2])
word = "level"
print(word == word[::-1])This prints .csv, report_2026, 2026, ABC, 123, and True. These show getting an extension, dropping it, taking a fixed-position field, splitting alternating characters, and a palindrome check.
For file extensions in real code, prefer str.endswith() or pathlib, because [-4:] assumes the extension is exactly four characters. Slicing is best when positions are known and fixed.
Edge cases and gotchas
- Characters, not bytes. Indexing counts Unicode characters, so
"café"[3]is"é". A later chapter on text and bytes explains how this differs from the encoded length. - Combined characters. Some visible symbols are built from several code points, such as a letter followed by a combining accent. Indexing treats each code point as one position, so a slice can separate a letter from its accent.
- Index must be an integer.
s[1.0]ands["1"]raiseTypeError. Convert withint()first. - Slice bounds may be computed. Expressions like
s[len(s) // 2:]work, because//returns an integer. Using/gives a float and raisesTypeError. - Slicing copies. A slice makes a new string, so slicing in a loop over a very long string can be costly. Prefer iterating directly or using string methods.
s = "Python"
try:
print(s[1.0])
except TypeError as e:
print("TypeError:", e)
print(s[len(s) // 2:])The first lookup raises TypeError because the index is a float. The last line prints hon.
Summary of rules
| Expression | Meaning | Out of range |
|---|---|---|
| `s[i]` | One character at index `i` | Raises `IndexError` |
| `s[a:b]` | Characters from `a` up to but not including `b` | Clamped, never raises |
| `s[a:b:k]` | Every `k`-th character in that range | Clamped, `k = 0` raises `ValueError` |
| `s[::-1]` | Reversed copy | Not applicable |
Exercises
Exercise
Given s = "programming", what do s[3:7], s[-4:], and s[::3] print?
Show answer
s[3:7] is gram, because indexes 3 to 6 are g, r, a, m. s[-4:] is ming, the last four characters. s[::3] takes indexes 0, 3, 6, 9, which are p, g, m, i, so it prints pgmi.
Exercise
Write an expression that returns the first character of a string text as a string, and returns an empty string (instead of raising an error) when text is empty.
Show answer
text[:1]. A slice is clamped to the string, so it returns "" for empty input, while text[0] would raise IndexError.
Exercise
What does "abcdef"[4:1:-1] return, and why does "abcdef"[1:4:-1] return an empty string?
Show answer
The first returns edc: it starts at index 4 (e), moves left, and stops before index 1. The second starts at index 1 and tries to move left toward index 4, which is on the other side, so no characters are selected.