String Indexing and Slicing#
Note
Source: Indexing table, subscript notation, and exercise adapted from the
C# edition (basicstringops/stringindexing.rst). Negative indices,
slicing, and step notation are Python-specific features drawn from the SE4ML
Python chapter (chapter_python.rst, lines 2512–2552).
Strings are sequences of characters. Python counts positions starting at
0, so the indices of the characters in "coding" are:
Index |
0 |
1 |
2 |
3 |
4 |
5 |
Character |
c |
o |
d |
i |
n |
g |
There are 6 characters and the last index is 5 — one less than the length.
Warning
The last valid index is len(s) - 1, not len(s).
Accessing s[6] on a six-character string raises an IndexError.
Subscript Notation#
Use square brackets to access a single character:
>>> s = "coding"
>>> s[0]
'c'
>>> s[2]
'd'
>>> s[5]
'g'
Unlike C#, Python has no separate char type — the result is always a
one-character string.
The subscript can be any expression that evaluates to an integer:
>>> n = 3
>>> s[n - 1]
'd'
Negative Indices#
Python allows negative indices that count from the right end:
>>> s = "coding"
>>> s[-1] # last character
'g'
>>> s[-2] # second from last
'n'
>>> s[-6] # same as s[0]
'c'
This is a convenience not available in C#. s[-1] is equivalent to
s[len(s) - 1].
Slicing#
A slice extracts a substring using the notation s[start:stop].
The result includes characters from index start up to, but not
including, index stop:
>>> s = "coding"
>>> s[1:4]
'odi'
>>> s[0:3]
'cod'
Omitting either end uses the beginning or end of the string:
>>> s[:3] # from the start
'cod'
>>> s[3:] # to the end
'ing'
>>> s[:] # whole string (copy)
'coding'
Slices work with negative indices too:
>>> s[-3:] # last three characters
'ing'
>>> s[:-2] # everything except the last two
'codi'
Step in Slices#
An optional third number specifies a step:
>>> s = "abcdefgh"
>>> s[::2] # every other character
'aceg'
>>> s[::-1] # reverse the string
'hgfedcba'
Reversing with [::-1] is an idiomatic Python trick worth remembering.
Indexing Exercise#
Predict what each line prints, then verify in the REPL:
s = "fragment"
k = 3
print(s[1])
print(s[k])
print(s[2 * k - 2])
print(s[-1])
print(s[2:5])
print(s[::-1])