Indexing and slicing

Part of the free LogicWiz Python course, Module 4: Strings. The examples and practice run in the app.

Kabir's roll number is '2026CS042'. The college app needs the year (2026), the branch (CS) and the number (042) as separate pieces, without anyone typing them again. One slice each.

You'll learn to

  • Pick out one character with a positive or negative index
  • Cut out a piece with `[start:stop:step]`, including negative steps
  • Reverse a string in one go
  • Explain why you can't change a character inside a string

Learn

Every character has two addresses

A string is a row of characters. Counting from the left starts at 0; counting from the right starts at -1.

S A M O S A
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

s[0] is the first character and s[-1] is the last. The last positive index is len(s) - 1, so s[6] here is an IndexError.

Indexing

s = "SAMOSA"
print(s[0], s[3], s[-1], s[-2])
print(len(s))
print(s[len(s) - 1])

Slicing: s[start:stop]

roll = "2026CS042"
print(roll[0:4])
print(roll[4:6])
print(roll[6:])
print(roll[:4] + "-" + roll[-3:])

Start is included, stop is not, exactly like range. Leave out start to begin at the front; leave out stop to go to the end. roll[-3:] means "the last three".

An index out of range crashes: "CHAI"[10] is IndexError: string index out of range. A slice out of range never crashes: "CHAI"[1:100] is just 'HAI', and "CHAI"[3:1] is the empty string ''.

The step, and going backwards

s[start:stop:step] jumps step characters at a time. s[::2] takes every second character.

A negative step walks right to left. Then the defaults flip: a missing start means the last character, and a missing stop means past the first character. So s[::-1] is the whole string reversed.

With a negative step, start must be to the right of stop, or you get ''.

Steps, forwards and backwards

s = "PYTHONIC"
print(s[::2])
print(s[::-1])
print(s[-3::-3])
print(s[5:1:-1])
print("[" + s[1:5:-1] + "]")

P Y T H O N I C are indexes 0-7. s[-3::-3] starts at index 5 (N), jumps back 3 to index 2 (T), and the next jump is off the front: 'NT'. s[1:5:-1] is empty because 1 is left of 5.

Board favourite: s[-3::-3], s[::-2], s[6:2:-2]. The safe method: write the indexes under every letter (positive and negative), circle the start, jump by the step, and stop before the stop index. Never do these in your head.

Strings are immutable

name = "kabir"
name[0] = "K"

TypeError: 'str' object does not support item assignment. A string can't be changed in place. Make a new string instead.

Build a new string instead

name = "kabir"
name = "K" + name[1:]
print(name)

code = "MH12AB1234"
masked = code[:4] + "****" + code[-2:]
print(masked)

name now points to a brand-new string 'Kabir'. The old 'kabir' was never changed.

In one line

s[0] first, s[-1] last; s[a:b] includes a but not b; s[::-1] reverses; strings can't be changed in place, so build a new one.