Indexing Basics
s = "PyForm" # P y F o r m # 0 1 2 3 4 5 print(s[0]) # P print(s[-1]) # m (negative indexes count from the end)
Slicing Syntax
s[start:stop:step]
The stop index is exclusive. Omitted values default to start=0, stop=len(s), step=1.
s = "PyForm" print(s[0:2]) # Py print(s[2:]) # Form print(s[:4]) # PyFo print(s[::2]) # PFr print(s[::-1]) # mroFyP (reverse)
Common Patterns
- First 3 chars:
s[:3] - Last 3 chars:
s[-3:] - Drop first char:
s[1:] - Drop last char:
s[:-1] - Reverse:
s[::-1]
Slicing Works on Lists Too
nums = [10, 20, 30, 40, 50] print(nums[1:4]) # [20, 30, 40] print(nums[::-1]) # [50, 40, 30, 20, 10]
Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ