Unit 11.2A · Term 2

String Indexing & Slicing

Strings in Python are sequences of characters. You can access individual characters by index and extract parts of a string using slicing. These skills are essential for text processing and manipulation.

Learning Objectives

  • 11.2.2.1 Use indexing in strings
  • 11.2.2.2 Apply slicing operations on strings

Lesson Presentation

11.2A-lesson-11-string-indexing.pdf · Slides for classroom use

Conceptual Anchor

The Train Car Analogy

A string is like a train where each car holds one character. Each car has a number (index), starting from 0. You can access any single car by its number (indexing) or request a sequence of cars (slicing). Negative indices count from the back of the train: car -1 is the last car.

Rules & Theory

String Indexing

# String: P y t h o n # Positive: 0 1 2 3 4 5 # Negative: -6 -5 -4 -3 -2 -1 s = "Python" print(s[0]) # P — first character print(s[5]) # n — last character print(s[-1]) # n — last character (negative index) print(s[-6]) # P — first character (negative index) print(len(s)) # 6 — length of string # IndexError if out of range # print(s[6]) # IndexError: string index out of range

String Slicing

# Syntax: string[start:stop:step] # start — inclusive (default 0) # stop — exclusive (default len) # step — default 1 s = "Programming" print(s[0:4]) # "Prog" — from index 0 to 3 print(s[4:7]) # "ram" — from index 4 to 6 print(s[:3]) # "Pro" — from start to index 2 print(s[7:]) # "ming" — from index 7 to end print(s[:]) # "Programming" — entire string (copy) # With step print(s[::2]) # "Pormig" — every 2nd character print(s[1::2]) # "rgamn" — every 2nd, starting at 1 # Reverse a string print(s[::-1]) # "gnimmargorP" # Negative indices in slicing print(s[-4:]) # "ming" — last 4 characters print(s[:-4]) # "Program" — all except last 4

Strings are Immutable

You cannot change individual characters: s[0] = "p" raises TypeError. Instead, create a new string: s = "p" + s[1:].

Worked Examples

1 Extracting Parts of a Date

date = "2025-02-19" year = date[:4] # "2025" month = date[5:7] # "02" day = date[8:] # "19" print(f"Day: {day}, Month: {month}, Year: {year}") # Day: 19, Month: 02, Year: 2025

2 Palindrome Check

word = input("Enter a word: ").lower() reversed_word = word[::-1] if word == reversed_word: print(f"'{word}' is a palindrome!") else: print(f"'{word}' is NOT a palindrome") # "racecar" → "racecar" → palindrome ✓ # "hello" → "olleh" → NOT palindrome ✗

3 Processing Each Character

text = "Hello World" # Method 1: iterate over characters for char in text: print(char, end="-") # H-e-l-l-o- -W-o-r-l-d- # Method 2: iterate by index for i in range(len(text)): print(f"Index {i}: '{text[i]}'") # Count uppercase letters upper_count = 0 for char in text: if char.isupper(): upper_count += 1 print("Uppercase letters:", upper_count) # 2

4 Masking Part of a String

email = "student@school.kz" at_pos = email.index("@") # Show first 2 chars, mask the rest before @ masked = email[:2] + "*" * (at_pos - 2) + email[at_pos:] print(masked) # "st*****@school.kz"

Pitfalls & Common Errors

Off-by-One in Slicing

s[1:4] gives characters at indices 1, 2, 3 — NOT 4. The stop index is always excluded.

Modifying Strings

s[0] = "X" raises TypeError. Strings are immutable. Create a new string instead.

Indexing with len()

A string of length 5 has indices 0-4. s[len(s)] is always an IndexError! Use s[len(s)-1] or s[-1] for the last character.

Pro-Tips for Exams

Quick Reference

  • s[-1] = last character (safer than s[len(s)-1])
  • s[::-1] = reverse a string (very common exam question!)
  • s[:n] = first n characters
  • s[n:] = everything from index n onwards
  • Slicing never causes IndexError (it just returns less)

Graded Tasks

Remember

For s = "Computer", what is s[0], s[-1], s[3], s[-3]?

Understand

Explain why s[1:5] returns 4 characters and not 5.

Apply

Write a program that extracts and prints the first name and last name from "LastName, FirstName".

Apply

Write a program to check if a word is a palindrome (case-insensitive) using slicing.

Analyze

What is the output of s = "abcdefgh"; print(s[1:7:2])? Trace step by step.

Create

Create a "string cipher" that takes every other character starting from index 0 and combines with every other character from index 1 reversed.

Self-Check Quiz

1. What does "Hello"[1] return?
Click to reveal answer
2. What does "Python"[::-1] return?
Click to reveal answer
3. What does "Hello"[1:4] return?
Click to reveal answer
4. Can you do "Hello"[0] = "J"?
Click to reveal answer
5. What does "Hello"[-2:] return?
Click to reveal answer