User:Siebengang/Workbench/Slicing!

Slicing strings (and lists)

edit

Strings can be cut into pieces — in the same way as it was shown for lists in the previous chapter — by using the slicing "operators" []. The slicing operator works in the same way as before: text[first_index:last_index] (in very rare cases there can be another colon and a third argument, as in the example shown below).

In order not to get confused by the index numbers, it is easiest to see them as "clipping places", possibilities to cut a sting into parts. Here is an example, which shows the clipping places (in yellow) and their index numbers (red and blue) for a simple text string:

0 1 2 ... -2 -1
text = " S T R I N G "
[: :]

Note that the red indexes are counted from the beginning of the string and the blue ones from the end of the string backwards. (Note that there is no blue -0, which could seem to be logical at the end of the string. Because -0 == 0, -0 means "beginning of the string" as well.) Now we are ready to use the indexes for slicing operations:

text[1:4] "TRI"
text[:5] "STRIN"
text[:-1] "STRIN"
text[-4:] "RING"
text[2] "R"
text[:] "STRING"
text[::-1] "GNIRTS"

text[1:4] gives us all of the text string between clipping places 1 and 4, "TRI". If you omit one of the [first_index:last_index] arguments, you get the beginning or end of the string as default: text[:5] gives "STRIN". For both first_index and last_index we can use both the red and the blue numbering schema: text[:-1] gives the same as text[:5], because the index -1 is at the same place as 5 in this case. If we do not use an argument containing a colon, the number is treated in a different way: text[2] gives us one character following the second clipping point, "R". The special slicing operation text[:] means "from the beginning to the end" and produces a copy of the entire string (or list, as shown in the previous chapter).

Last but not least, the slicing operation can have a second colon and a third argument, which is interpreted as the "step size": text[::-1] is text from beginning to the end, with a step size of -1. -1 means "every character, but in the other direction". "STRING" backwards is "GNIRTS" (test a step length of 2, if you have not got the point yet).

All these slicing operations work with lists as well. In that sense strings are just a special case of lists, where the list elements are single characters.