Going Deeper with Strings

Read this for more on strings.

4. String slices

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

>>> s = 'Monty Python'
>>> s[0:5]
>>> s[6:12]
The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in Figure 8.1.

Figure 8.1: Slice indices.

Figure 8.1: Slice indices. 

If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:
>>> fruit = 'banana'
>>> fruit[:3]
>>> fruit[3:]

If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:
>>> fruit = 'banana'
>>> fruit[3:3]
An empty string contains no characters and has length 0, but other than that, it is the same as any other string. Continuing this example, what do you think fruit[:] means? Try it and see.