To find items corresponding to a particular slice, you use the name of the string and brackets, as above. Inside the brackets, you enter a slice expression: the beginning of the slice, a colon, and the end of the slice. The end of the slice means "up to but not including" this element. In the example below, five elements are returned (index numbers

Here's an example:

A step (sometimes called a stride) skips over some items in the sequence. To specify a step, type a second colon and the step number, like so:

>>>> mystring =

' 123456789'

>>> mystring[0:9 :

■ 2]


Steps aren't supported in versions of Python earlier than 2.3. Figuring out the tricks

Following are some shortcuts you can use with slicing and indexing syntax. The examples all use this string:

• The beginnings and ends of slices are like notebook dividers—they sit between the elements.

• If you are counting from left to right when indexing or slicing, the first index number is 0, not 1, as shown:

Tip When slicing, the first index defaults to 0. If you leave out the first index, Python uses the first item in the sequence, like this:

• When slicing, the last index defaults to "the length of the sequence." You can access the last item when slicing by leaving out the number after the colon, like this:

Tip If you use a number larger than the size of the sequence, "the length of the sequence" replaces it.

• However, this doesn't work with indexing. If you use a number larger than the size of the sequence, Python raises an IndexError.

• Traceback (most recent call last):

• File "<stdin>", line 1, in <module>

• IndexError: string index out of range

• If you are slicing, and the second index number is smaller than the first, you get an empty sequence (for example, an empty string).

You can also count from right to left when indexing or slicing. (This is called negative indexing.) When indexing, the first index number, from the right, is -1, the next is -2, and so on—but the leftmost index is still 0.

If you are making a slice, however, -1 points before the last element. To get at the last element, you need to use ":]":

To get the whole sequence as a slice, use [:] (which makes a copy).

Specifying a negative step when slicing is one way to reverse a string.

Figure 6-1 shows the relationship of index numbers and elements in a string or other sequence object.

H i therei "

5Mil frwi l»P? I» r1|»t 5"ti IrflMl, fro rl,n!- I» Hit

Figure 6-1: Relationship of indexes, slice indexes, and elements in a sequence object.

Was this article helpful?

0 0

Post a comment