Skip to content

Computer Science · Ch 8 — Strings

Slicing

8.3.4

Slicing

Slicing is the operation that extracts a part of a string — a substring — by specifying an index range instead of a single index. Where indexing (Section 8.2.1) fetches one character, a slice fetches a run of consecutive characters as a new string.

The basic slice: s[n:m]

For a string s, the slice s[n:m] returns the part of s starting at index n (inclusive) and ending at index m (exclusive) — that is, all the characters from s[n] up to and including s[m-1]. The character at index m itself is not included. Consequently, the number of characters in the slice always equals the difference of the two indices, m - n.

>>> s = 'Hello World!'
>>> s[1:5]        # characters at indices 1,2,3,4  ->  5-1 = 4 chars
'ello'
>>> s[7:10]       # characters at indices 7,8,9
'orl'

Out-of-range and reversed indices do not raise errors

Unlike plain indexing, slicing is forgiving:

  • an end index that is too big is quietly truncated to the end of the string;
  • a first index larger than the second yields an empty string '' rather than an error.
>>> s[3:20]       # 20 is beyond the end -> truncated to the end
'lo World!'
>>> s[7:2]        # start after end -> empty string
''

Omitting an index

Either index (or both) may be left out, and Python fills in the natural default:

  • First index omitted — the slice starts from index 0 (the beginning):
>>> s[:5]         # from the start up to index 4
'Hello'
  • Second index omitted — the slice runs to the end of the string (up to its full length):
>>> s[6:]         # from index 6 to the end
'World!'

The third index: step size

A slice can take a third index specifying the step size: s[n:m:k] extracts every k-th character from s, starting at index n and ending at m-1. When the step is not given, it defaults to 1 (take every character).

>>> s[0:10:2]     # every 2nd character of indices 0..9
'HloWr'
>>> s[0:10:3]     # every 3rd character of indices 0..9
'HlWl'

Negative indices in slices

Negative indexing (counting from the right, Section 8.2.1) works inside slices too. The same inclusive-start / exclusive-end rule applies:

>>> s[-6:-1]      # characters at indices -6,-5,-4,-3,-2
'World'

Reversing a string with a negative step …