Sub topic 3
Negative Steps and Reversing a String
Assume you know string literals, variables, print(), len(), and basic try/except. Python strings are immutable sequences of Unicode code points. A slice reads part of a string; it does not modify the original.
Negative steps and reversing a string
A slice has the form text[start:stop:step]. The stop position is excluded. A negative step moves from right to left.
s = "abcdefghij"
print(s[::2]) # acegi
print(s[1::2]) # bdfhj
print(s[::-1]) # jihgfedcba
print(s[7:2:-2]) # hfdFor s[7:2:-2], Python visits indexes 7, 5, and 3. It stops before index 2.
Strings cannot be changed in place
Index assignment raises TypeError because strings are immutable. Build a new string with concatenation or slices.
s = "Python"
updated = "J" + s[1:]
print(updated) # JythonThe expression s[1:] creates the part after the first character. Concatenation creates a separate string.
> callout note > For a negative step, choose a start near the right side and a stop to its left. An omitted start or stop uses a direction-aware default.
Everyday slicing patterns
| Goal | Expression | Result for `"Python"` |
|---|---|---|
| First three characters | `s[:3]` | `"Pyt"` |
| Last three characters | `s[-3:]` | `"hon"` |
| Every second character | `s[::2]` | `"Pto"` |
| Reverse the string | `s[::-1]` | `"nohtyP"` |
Out-of-range slice bounds are clamped, so s[2:100] works. In contrast, s[100] raises IndexError.
Slice objects and `slice.indices()`
A slice object stores slicing rules for reuse. Its indices(length) method resolves omitted and negative bounds for a particular sequence length.
s = "Python"
last_three = slice(-3, None)
print(s[last_three]) # hon
print(last_three.indices(len(s))) # (3, 6, 1)
print(slice(None, None, -1).indices(6)) # (5, -1, -1)Code points versus visible characters
Indexing operates on Unicode code points, not necessarily on visible characters. A combining accent can use a separate code point.
s = "cafe\u0301"
print(len(s)) # 5
print(s[:4]) # cafeThe displayed word may look like four characters even though the string contains five code points.
Exercise
What does "abcdef"[4:1:-1] produce?
Show answer
It produces "edc", using indexes 4, 3, and 2 before stopping at index 1.