next up previous contents
Next: Functions and Methods for Up: String Operations Previous: Repetition   Contents


Indexing and Slicing

Strings in python support indexing and slicing. To extract a single character from a string, follow the string with the index of the desired character surrounded by square brackets ([ ]), remembering that the first character of a string has index zero.
>>> what = 'This parrot is dead'
>>> what[3]
's'
>>> what[0]
'T'
If the subscript you provide between the brackets is less than zero, python counts from the end of the string, with a subscript of -1 representing the last character in the string.
>>> what[-1]
'd'

To extract a contiguous piece of a string (known as a slice), use a subscript consisting of the starting position followed by a colon (:, finally followed by one more than the ending position of the slice you want to extract. Notice that the slicing stops immediately before the second value:

>>> what[0:4]
'This'
>>> what[5:11]
'parrot'
One way to think about the indexes in a slice is that you give the starting position as the value before the colon, and the starting position plus the number of characters in the slice after the colon.

For the special case when a slice starts at the beginning of a string, or continues until the end, you can omit the first or second index, respectively. So to extract all but the first character of a string, you can use a subscript of 1: .

>>> what[1:]
'his parrot is dead'
To extract the first 3 characters of a string you can use :3 .
>>> what[:3]
'Thi'
If you use a value for a slice index which is larger than the length of the string, python does not raise an exceptrion, but treats the index as if it was the length of the string.

As always, variables and integer constants can be freely mixed:

>>> start = 3
>>> finish = 8
>>> what[start:finish]
's par'
>>> what[5:finish]
'par'

Using a second index which is less than or equal to the first index will result in an empty string. If either index is not an integer, a TypeError exception is raised unless, of course, that index was omitted.


next up previous contents
Next: Functions and Methods for Up: String Operations Previous: Repetition   Contents
Phil Spector 2003-11-12