1. Slicing with [start:stop:step]
Half-Open Intervals & Negative Step Strides
- String indexing starts at 0 for positive indices and -1 for the last character.
- Slices use half-open intervals [start:stop): the element at stop is excluded.
- A negative step reverses the direction of traversal: s[::-1] creates a reversed string.
- Slicing never raises an IndexError; it gracefully clamps out-of-range indices.
text = "PythonLab"
print("First 4:", text[:4]) # 'Pyth'
print("Index 2 to 6:", text[2:6]) # 'thon'
print("Every 2nd char:", text[::2]) # 'PtoL'
print("Reversed:", text[::-1]) # 'baLnohtyP'
💡 Key Takeaway: The slice notation [start:stop:step] provides O(k) substring extraction where k is the slice length.