Sub topic 11
Everyday slicing patterns
This chapter assumes you already know zero-based and negative indexes, the s[start:stop:step] form, how omitted bounds work, and that strings are immutable. Here you combine those pieces into patterns you will use all the time. You will also learn which edge cases make them fail.
Why patterns are worth learning
A slice expression is short, but each one hides a decision about which characters to keep. A small set of reusable shapes lets you read and write slices without recounting indexes each time. Every pattern below returns a new string. The original is never changed.
The diagram groups the patterns by the question you are asking.
Taking and dropping the ends
The most common job is keeping or discarding a known number of characters at the start or end.
name = "report_2026.csv"
print(name[:6]) # first 6 characters
print(name[-3:]) # last 3 characters
print(name[:-4]) # everything except the last 4
print(name[1:-1]) # everything except first and last
print(name[7:11]) # a fixed middle sectionThis prints report, csv, report_2026, eport_2026.cs and 2026.
Two rules cover most cases:
s[:n]keeps the firstncharacters.s[n:]drops them.s[-n:]keeps the lastncharacters.s[:-n]drops them.
Each pair splits the string at the same position, so s[:n] + s[n:] == s always holds. That property is a quick check that you chose the right bounds.
The `-0` trap
When n is a variable, -n can become -0, and -0 is just 0. This breaks the last-n and drop-last-n patterns when n is zero.
text = "Python"
n = 0
print(repr(text[-n:])) # 'Python', not ''
print(repr(text[:-n])) # '', not 'Python'Both results are the opposite of what the code intends. Handle zero explicitly, or use helper functions that do.
def last_n(text, n):
if n <= 0:
return ""
return text[-n:]
def drop_last_n(text, n):
return text[:max(len(text) - n, 0)]
print(repr(last_n("Python", 2)))
print(repr(last_n("Python", 0)))
print(repr(last_n("Python", 10)))
print(repr(drop_last_n("Python", 2)))
print(repr(drop_last_n("Python", 0)))
print(repr(drop_last_n("Python", 10)))The output is 'on', '', 'Python', 'Pyth', 'Python' and ''. Slices clamp bounds that are too large, so asking for more characters than exist returns the whole string without an error. The max(..., 0) guard is needed in drop_last_n because len(text) - n can go negative. A negative stop would count from the end and give the wrong answer.
Every nth character and reversing
A step skips characters, and a negative step walks backwards.
s = "abcdefghij"
print(s[::2]) # even positions
print(s[1::2]) # odd positions
print(s[::3]) # every third character
print(s[::-1]) # reversedThis prints acegi, bdfhj, adgj and jihgfedcba.
You can use [::-1] on lists and tuples too. That lets you reverse the order of words while leaving each word alone.
sentence = "slicing is a useful skill"
words = sentence.split()
print(" ".join(words[::-1]))
print(" ".join(word[::-1] for word in words))The first line prints skill useful a is slicing. The second prints gnicils si a lufesu lliks, because each word is reversed in place and the word order is kept.
Palindromes that ignore punctuation
The earlier palindrome check compares a string with its reverse. Real text has spaces and punctuation, so filter it first.
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("Slicing"))This prints True and then False. An empty string counts as a palindrome with this function, which is usually the convention you want.
Splitting at a position and rejoining
Because s[:i] + s[i:] rebuilds the original, you can insert or remove text at position i by changing what sits between the two pieces.
digits = "5551234567"
formatted = f"({digits[:3]}) {digits[3:6]}-{digits[6:]}"
print(formatted)
card = "4111111111111111"
masked = "*" * (len(card) - 4) + card[-4:]
print(masked)The first line prints (555) 123-4567. The second prints ************1111. In the masking example, len(card) - 4 is zero or negative for very short strings, and multiplying a string by a non-positive number gives an empty string, so it does not raise an error.
Rotating a string
Moving characters from one end to the other is a split and swap of the two halves.
def rotate(text, k):
if not text:
return text
k %= len(text)
return text[k:] + text[:k]
print(rotate("abcdef", 2))
print(rotate("abcdef", -1))
print(rotate("abcdef", 8))This prints cdefab, fabcde and cdefab. The %= step keeps k inside the string's length, so a rotation of 8 on 6 characters behaves like a rotation of 2. Negative values rotate the other way, because Python's % gives a non-negative result for a positive divisor. The early return avoids a division by zero on an empty string.
Replacing one character
Strings cannot be assigned to by index, so you build a new string from the part before the position, the replacement, and the part after.
def replace_at(text, i, ch):
if not -len(text) <= i < len(text):
raise IndexError("string index out of range")
if i < 0:
i += len(text)
return text[:i] + ch + text[i + 1:]
print(replace_at("Python", 0, "J"))
print(replace_at("Python", -1, "!"))This prints Jython and Pytho!.
The normalization step matters. Suppose you skipped it and used i = -1 directly. The expression text[:-1] + ch + text[0:] would keep the whole string after the new character, because i + 1 is 0. The result would be Pythonn-style duplication rather than a replacement. Convert a negative index to its non-negative equivalent first, then slice.
The range check restores the error a normal index would raise. Without it, an out-of-range i would be silently clamped by the slices and the function would return a misleading result.
Checking and removing prefixes and suffixes
You can test for a prefix with a slice, but there are clearer tools.
filename = "report_2026.csv"
prefix = "report_"
print(filename[:len(prefix)] == prefix)
print(filename.startswith(prefix))
print(filename.endswith(".csv"))
print(filename.removeprefix(prefix))
print(filename.removesuffix(".csv"))All of the first three lines print True. The last two print 2026.csv and report_2026. The methods removeprefix and removesuffix need Python 3.9 or later.
Prefer the methods when they fit. A hand-written filename[:-4] removes four characters whether or not they are .csv. It silently damages a name like notes.txt, which removesuffix(".csv") would leave untouched. Use slices when the position is the point, such as fixed-width records. Use methods when the content is the point.
Fixed-size chunks
A range with a step produces the start of each chunk, and a slice cuts it out. The final chunk is shorter when the length is not a multiple of the size.
def chunks(text, size):
if size <= 0:
raise ValueError("size must be positive")
return [text[i:i + size] for i in range(0, len(text), size)]
print(chunks("abcdefghij", 4))
print(chunks("abc", 5))
print(chunks("", 3))This prints ['abcd', 'efgh', 'ij'], ['abc'] and []. No bounds check is needed for the last chunk, because the stop value i + size is clamped to the end of the string.
Quick reference
| Goal | Pattern | Watch out for |
|---|---|---|
| First `n` characters | `s[:n]` | Safe for any `n` of zero or more |
| Last `n` characters | `s[-n:]` | Returns the whole string when `n` is 0 |
| Drop first `n` | `s[n:]` | Safe for any `n` of zero or more |
| Drop last `n` | `s[:-n]` | Returns `''` when `n` is 0 |
| Every `k`th character | `s[::k]` | `k` must not be 0, which raises `ValueError` |
| Reverse | `s[::-1]` | Reverses code points, not visible characters |
| Copy with one change | `s[:i] + x + s[i+1:]` | Normalize negative `i` first |
| Chunks of size `k` | `s[i:i+k]` in a loop | The last chunk may be shorter |
Common mistakes
- Off-by-one stops. The stop index is excluded, so
s[2:5]has three characters. The length of a slice with step 1 isstop - start, as long as both are within range. - Mixing signs. In
s[2:-2]the start counts from the front and the stop counts from the back. That is legal and useful, but it returns an empty string when the two bounds cross, for example on"abc". - Forgetting that
[::-1]is a copy. It builds a new string. For a very long string that costs memory proportional to its length. Usereversed(s)when you only need to loop backwards. - Assuming a result has a fixed length. When the input might be shorter than your bounds, slices return less without complaint. Check
len()if the length matters.
Exercises
Exercise
Predict the output, then explain why the second line differs from what a reader might expect. text = "Python" n = 0 print(repr(text[:n])) print(repr(text[-n:]))
Show answer
The first line prints '' because text[:0] stops before index 0, so nothing is kept. The second line prints 'Python', because -0 equals 0 and text[0:] starts at the beginning and keeps everything. Code that means "the last n characters" must treat n == 0 as a special case and return an empty string.
Exercise
Write a function swaphalves(text) that returns the second half followed by the first half. For odd lengths, the extra character belongs to the second half. What does swaphalves("abcde") return?
Show answer
Use mid = len(text) // 2, then return text[mid:] + text[:mid]. For "abcde", mid is 2, so the result is "cde" + "ab" = "cdeab". For an empty string, mid is 0 and the result is the empty string, so no special case is needed.