Sub topic 5
Slicing with Start and Stop
This chapter assumes you can run Python code in a REPL or script, assign a string literal to a variable, use print() and len(), and read a simple try/except block. It also assumes you know that s[0] is the first character and s[-1] is the last. Here you will learn how s[start:stop] selects a run of characters and how to predict its result without trial and error.
What a slice does
An index gives you one character. A slice gives you a new string made of a run of consecutive characters. You write it with two numbers separated by a colon inside square brackets:
s = "Python"
print(s[0:2])
print(s[2:5])
print(s[1:4])This prints Py, tho and yth. The two numbers are the start and the stop. The slice begins at the character at index start and ends just before the character at index stop.
Here are the indexes for "Python":
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
For s[2:5] you start at index 2 (t), take index 3 (h) and index 4 (o), and stop before index 5. The result is tho.
The half-open rule
A slice is half-open: it includes start and excludes stop. People often find this surprising at first, so it is worth knowing why it is useful.
The most useful consequence is that the length of the result is stop - start. In s[2:5] the length is 3, and tho has three characters. You never have to add or subtract 1.
s = "Python"
start, stop = 1, 4
piece = s[start:stop]
print(piece)
print(len(piece))
print(stop - start)This prints yth, then 3, then 3.
Two slices that share a boundary join up with no gap and no overlap. If you cut at index 3, the first piece ends where the second begins:
s = "Python"
left = s[0:3]
right = s[3:6]
print(left)
print(right)
print(left + right == s)This prints Pyt, hon and True. The boundary value 3 appears as the stop of the first slice and as the start of the second. With an inclusive stop you would need s[0:2] and s[3:5], and the two numbers would not match.
A helpful mental picture is that the numbers point at the gaps between characters, not at the characters themselves. Index 0 is the gap before P, index 1 is the gap between P and y, and so on up to index 6, the gap after n. A slice takes everything between two gaps.
Negative start and stop
Slice bounds accept negative numbers with the same meaning as in indexing. Python adds len(s) to a negative bound before it slices. For "Python", the length is 6, so -4 becomes 2 and -1 becomes 5.
s = "Python"
print(s[-4:-1])
print(s[1:-1])
print(s[-3:5])This prints tho, ytho and ho.
s[-4:-1]is the same ass[2:5].s[1:-1]drops the first and last characters. This is a common way to remove surrounding quotes or brackets.s[-3:5]mixes the two styles. The start becomes 3 and the stop is 5, so you get indexes 3 and 4.
The half-open rule still holds with negative numbers. The stop -1 excludes the last character, so s[1:-1] never contains n. You cannot include the last character by using a negative stop. To reach the end you need a stop equal to len(s), or you leave the stop out, which a later chapter covers.
Here is how Python evaluates s[a:b]:
The diagram leaves out clamping, which applies when a bound still falls outside the string after step one. A later chapter covers that case.
The `-0` trap
Because negative bounds count back from the end, it is tempting to write -0 to mean "the end". That does not work, because -0 is just 0.
s = "Python"
print(repr(s[-3:-0]))
print(repr(s[-3:0]))
print(s[-3:len(s)])This prints '', '' and hon. Both of the first two slices have a stop of 0, which is before the start of 3, so the result is empty. Use len(s) as the stop when you need to include the last character.
Empty and single-character results
When start equals stop, the slice is empty, because there is nothing between a gap and itself. When start is greater than stop, the result is also empty. A slice does not raise an error for this.
s = "Python"
print(repr(s[4:4]))
print(repr(s[2:3]))
print(type(s[2:3]))This prints '', 't' and <class 'str'>. A one-character slice is a string, just like the result of s[2]. Python has no separate character type.
The difference between s[2] and s[2:3] shows up when the position is out of range. An index raises IndexError, but a slice returns a string. A later chapter explains that difference in detail.
Slices always make a new string
A slice builds a new string. It does not modify s and it is not a live view of it. Changing what s refers to later does not change a slice you took earlier.
s = "Python"
piece = s[0:2]
s = "Rust"
print(piece)
print(s)This prints Py and Rust. Strings are immutable, so there is no way for a slice to change the original in the first place.
Worked patterns with start and stop
Fixed-width fields
When data has a fixed layout, you can slice by position:
date = "2026-11-26"
year = date[0:4]
month = date[5:7]
day = date[8:10]
print(year, month, day)This prints 2026 11 26. The - characters sit at indexes 4 and 7, so each field starts one past a separator. Because of the half-open rule, each stop is the start plus the field width: 5 + 2 = 7 and 8 + 2 = 10.
Cutting around a found position
Methods such as str.index() return a position, and you can feed that position into a slice:
filename = "report_2026.csv"
dot = filename.index(".")
name = filename[0:dot]
extension = filename[dot + 1:len(filename)]
print(name)
print(extension)This prints report_2026 and csv. The first slice stops at the dot, so the dot is excluded. The second starts one past the dot, so it is excluded there too. Using dot as a stop and dot + 1 as a start is a typical way to drop a separator.
Start plus width
When you know where a piece starts and how long it is, use start + width as the stop:
def window(text, start, width):
return text[start:start + width]
print(window("abcdefgh", 2, 3))This prints cde. The length rule guarantees the result has width characters, as long as the slice does not run past the end of the string.
Sliding windows
Repeating that pattern in a loop gives every run of a fixed length:
text = "abcde"
size = 3
for i in range(len(text) - size + 1):
print(text[i:i + size])This prints abc, bcd and cde. The + 1 in the loop bound is needed because the last valid start is len(text) - size, and range excludes its own stop. This is the same half-open convention applied to range.
Removing both ends
wrapped = "(hello)"
print(wrapped[1:-1])This prints hello. The start skips the opening bracket and the negative stop skips the closing one, whatever the string length.
Common mistakes
- Reading the stop as inclusive. Expecting
s[1:4]to contain the character at index 4 gives results that are one character too short. Countstop - startto check the length. - Using the wrong end for a negative stop.
s[0:-1]leaves out the last character. It does not mean "the whole string". - Confusing
s[a:b]withs[a, b]. A comma inside the brackets passes a tuple to the string, which raisesTypeError. Use a colon. - Passing a float. Slice bounds must be integers (or objects with an
__index__method).s[0:2.0]raisesTypeError. Use//orint()when a bound comes from a division. - Expecting an error when the bounds are reversed.
s[4:2]returns an empty string. If you get''when you expected text, check that the start is smaller than the stop after negative bounds have been converted.
Summary of the rules
s[start:stop]includes the character atstartand excludes the one atstop.- Within the string, the result has
stop - startcharacters. - A negative bound is converted by adding
len(s). - A slice returns a new
strand never changes the original. - When the start is not before the stop, the result is
''.
Exercise
Given s = "programming", what does s[3:-4] return, and how many characters does it have? Show how you worked it out.
Show answer
The length of "programming" is 11, so the stop -4 becomes 11 - 4 = 7. The slice is s[3:7], which takes indexes 3, 4, 5 and 6 (g, r, a, m). The result is "gram", and its length is 7 - 3 = 4.
Exercise
Write a slice expression that takes "abcdef" and returns "cde", first using only positive bounds and then using a negative stop.
Show answer
With positive bounds, "abcdef"[2:5] returns "cde". With a negative stop, "abcdef"[2:-1] also returns "cde", because -1 becomes 6 - 1 = 5.
Exercise
A string is "ID-4821-X". Use slices with start and stop to extract "4821" and explain why the start is 3 and the stop is 7.
Show answer
Use s[3:7]. The characters I, D and - occupy indexes 0, 1 and 2, so the digits start at index 3. There are four digits, so the stop is 3 + 4 = 7. Index 7 is the second "-", which is excluded by the half-open rule.