Sub topic 11
Everyday slicing patterns
This chapter assumes you know how indexes and slices work, including negative indexes, omitted bounds and steps. It collects the slice expressions you will use most often, and the mistakes that go with them.
The core patterns
Most real slicing is one of a few shapes. The table uses s = "Python".
| Goal | Expression | Result |
|---|---|---|
| First 2 characters | `s[:2]` | `Py` |
| Last 3 characters | `s[-3:]` | `hon` |
| Drop the first character | `s[1:]` | `ython` |
| Drop the last character | `s[:-1]` | `Pytho` |
| Every other character | `s[::2]` | `Pto` |
| Reverse | `s[::-1]` | `nohtyP` |
| Shallow copy | `s[:]` | `Python` |
A copy made with s[:] is rarely useful for strings. Strings are immutable, so there is nothing to protect from changes.
Cutting up a known format
Slices work well on fixed-width text, such as codes, dates or file names. Count positions from the start for the front of the string. Count from the end for the part whose length varies.
name = "report_2026.txt"
print(name[:6]) # report
print(name[7:11]) # 2026
print(name[-3:]) # txt
print(name[:-4]) # report_2026Slicing with [:-4] assumes a three-letter extension. For arbitrary names, removesuffix(".txt") (Python 3.9+) or os.path.splitext states the intent better and does not break when the suffix changes length.
Reverse and compare
Combining a reversed slice with a comparison gives a short palindrome check. Normalize the text first so that case and punctuation do not matter.
def is_palindrome(text):
cleaned = "".join(ch for ch in text.lower() if ch.isalnum())
return cleaned == cleaned[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("Python"))This prints True and then False.
Editing by building a new string
Because s[0] = "J" raises TypeError, an edit means joining the part before the change, the new text and the part after it. Replacing one character looks like this:
def replace_at(text, index, new):
if index < 0:
index += len(text)
return text[:index] + new + text[index + 1:]
print(replace_at("Python", 0, "J"))
print(replace_at("Python", -1, "N"))The output is Jython and then PythoN. To insert instead of replace, use text[:i] + new + text[i:]. To delete one character, use text[:i] + text[i + 1:].
Common errors
The first error is -0. The integer -0 is just 0, so a negative-index formula can fail when the count is zero. In replace_at, passing -1 without the adjustment above computes text[:-1] + new + text[0:]. That puts the whole string after your change. A "last n characters" helper has the same problem:
def last_n(text, n):
return text[-n:] if n else ""
print(repr(last_n("Python", 3)))
print(repr(last_n("Python", 0)))Without the if n guard, "Python"[-0:] returns the whole string. It does not return an empty one.
The second error is trusting out-of-range slices to catch mistakes. s[:100] and s[10:] raise no error, so an off-by-one in a computed bound can silently give "" or a shorter result. Check len(s) yourself when the length matters.
The third error is the off-by-one in the stop value. The stop is excluded, so s[a:b] has length b - a (when both bounds are in range). Use that to check your arithmetic: name[7:11] is 11 - 7 = 4 characters.
Choosing between slices and methods
Slices work on position. Methods such as startswith, removeprefix, split and partition work on content. Use a slice when the layout is fixed. Use a method when you are looking for a marker. Writing line[len("ID:"):] repeats a magic number and breaks when the prefix changes, while line.removeprefix("ID:") does not.
Exercise
Given code = "AB-1234-XY", write slice expressions that return the middle number "1234", the last two letters "XY", and the whole code reversed. What does code[-0:] return?
Show answer
code[3:7] gives "1234", code[-2:] gives "XY", and code[::-1] gives "YX-4321-BA". code[-0:] returns the whole string "AB-1234-XY", because -0 equals 0, so the slice starts at the beginning.