>> Module 02 / Day 17 / Lecture

Slicing & Indexing

Reaching inside a string
Yesterday you reshaped whole strings. Today you reach inside them — grab one character, or a whole slice, by position.
Lecture
75 min · 09:00–10:15
Lab
60 min · Palindrome + Initials
Module
M2 · Python in Practice
DAY 17 / 40
>> Today's roadmap

Five stops, then a lab

  1. A string is a numbered sequence of characters
  2. Indexing — s[0], and counting backwards with s[-1]
  3. Slicing — s[2:5], the "up-to-but-not-including" rule
  4. The step — s[::2] and the famous reverse s[::-1]
  5. Two classics — palindrome check & initials extractor
  6. Lab — build both
>> 01 / 05 · The mental model

Every character has a number

Think of a string as boxes in a row. Counting starts at 0, not 1. You can also count from the right with negative numbers.

P
0
-6
y
1
-5
t
2
-4
h
3
-3
o
4
-2
n
5
-1
>> 02 / 05 · Indexing

Grab one character with s[i]

indexing.py
word = "Python"

word[0]    # 'P'  — first character
word[2]    # 't'
word[-1]   # 'n'  — last character
word[-2]   # 'o'  — second from the end

word[10]   # IndexError — there's no box 10
The handy trick.
s[-1] is the cleanest way to get the last character — no need to know the length.
>> 03 / 05 · Slicing

Grab a range with s[start:stop]

Takes from start up to but not including stop. That "not including" trips up everyone at first.

slicing.py
word = "Python"   #  P y t h o n
                  #  0 1 2 3 4 5
word[0:2]   # 'Py'   — boxes 0 and 1 (NOT 2)
word[2:5]   # 'tho'  — boxes 2,3,4
word[:3]    # 'Pyt'  — no start = from 0
word[3:]    # 'hon'  — no stop  = to the end
word[:]     # 'Python' — a full copy
>> 04 / 05 · The third number

The step — s[start:stop:step]

step.py
s = "ABCDEFGH"

s[::2]    # 'ACEG' — every 2nd character
s[1::2]   # 'BDFH' — every 2nd, from index 1

s[::-1]   # 'HGFEDCBA' — REVERSED 🔁
THE FAMOUS ONE

s[::-1] is the Python idiom for reverse a string. A negative step walks backwards. You'll use it in the palindrome check.

>> 05 / 05 · Classic #1

Palindrome check

A palindrome reads the same forwards and backwards — level, madam, racecar. So: is the string equal to its own reverse?

palindrome.py
def is_palindrome(text):
    clean = text.lower().replace(" ", "")  # reuse D16!
    return clean == clean[::-1]            # reverse & compare

print(is_palindrome("Racecar"))     # True
print(is_palindrome("hello"))       # False
print(is_palindrome("Never odd or even"))  # True
>> Classic #2

Initials extractor

Take a full name, grab the first letter of each word, and stitch them into uppercase initials. Split (D16) + indexing (D17) together.

initials.py
def initials(full_name):
    letters = []
    for word in full_name.split():   # ['Aisha', 'Noor', 'Khan']
        letters.append(word[0])      # first char of each
    return "".join(letters).upper()  # 'ANK'

print(initials("aisha noor khan"))  # 'ANK'
>> Common failures

Four mistakes you'll make today

  1. Starting from 1 — Python counts from 0, so the first char is s[0].
  2. Expecting s[2:5] to include index 5 — stop is excluded.
  3. s[10] on a short string → IndexError. (But slicing past the end is safe!)
  4. Trying s[0] = "X" to change a letter → TypeError; strings are immutable (build a new one).
>> 11:00 – 12:00 · Lab

Today's lab — Palindrome + Initials

PROBLEM 1
Palindrome Checker

Read a word or phrase and report whether it's a palindrome, ignoring case and spaces.

PROBLEM 2
Initials Maker

Turn a full name into uppercase initials. ★ format them as "A.N.K." with dots.

>> End of Day 17

What you can now do

  • ✓ Grab any character with s[i] — including s[-1] from the back.
  • ✓ Slice ranges with s[start:stop:step] and reverse with s[::-1].
  • ✓ Combine split, index, and join to solve real text problems.
01 / 11
←/→ navigate   F fullscreen   Ctrl/⌘+P save as PDF