s[0], and counting backwards with s[-1]s[2:5], the "up-to-but-not-including" rules[::2] and the famous reverse s[::-1]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.
"Python"[0] is 'P'; "Python"[-1] is 'n'.
s[i]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
s[-1] is the cleanest way to get the last character — no need to know the length.
s[start:stop]
Takes from start up to but not including stop. That "not including" trips up everyone at first.
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
s[2:5] gives 5 - 2 = 3 characters. The math always works out to stop - start.
s[start:stop:step]s = "ABCDEFGH"
s[::2] # 'ACEG' — every 2nd character
s[1::2] # 'BDFH' — every 2nd, from index 1
s[::-1] # 'HGFEDCBA' — REVERSED 🔁
s[::-1] is the Python idiom for reverse a string. A negative step walks backwards. You'll use it in the palindrome check.
A palindrome reads the same forwards and backwards — level, madam, racecar. So: is the string equal to its own reverse?
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
.lower() and .replace() team up with today's [::-1]. The skills stack.
Take a full name, grab the first letter of each word, and stitch them into uppercase initials. Split (D16) + indexing (D17) together.
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'
.split() to break it up, word[0] to index, .join() to rebuild. This is what "Python in practice" looks like.
0, so the first char is s[0].s[2:5] to include index 5 — stop is excluded.s[10] on a short string → IndexError. (But slicing past the end is safe!)s[0] = "X" to change a letter → TypeError; strings are immutable (build a new one).Read a word or phrase and report whether it's a palindrome, ignoring case and spaces.
Turn a full name into uppercase initials. ★ format them as "A.N.K." with dots.
students/<your-username>/D17_slicing.py. Full brief in lab/module_2_practice/D17_slicing/problem.md. PR before 12:00.
s[i] — including s[-1] from the back.
s[start:stop:step] and reverse with s[::-1].
list operations on Day 18.