Page 76 - Python Basics: A Practical Introduction to Python 3
P. 76

4.2. Concatenation, Indexing, and Slicing


            whose index is the first number in the slice and ends with the last char-
            acter in the string:

            >>> flavor[3:]
            ' pie'

            For "fig pie", the slice [3:] is equivalent to the slice [3:7]. Since the
            character at index 3 is a space, flavor[3:9] returns the substring that
            starts with the space and ends with the last letter: " pie".

            If you omit both the first and second numbers in a slice, you get a
            string that starts with the character at index 0 and ends with the last
            character. In other words, omitting both numbers in a slice returns
            the entire string:

            >>> flavor[:]
            'fig pie'

            It’s important to note that, unlike with string indexing, Python won’t
            raise an IndexError when you try to slice between boundaries that fall
            outside the beginning or ending boundaries of a string:


            >>> flavor[:14]
            'fig pie'
            >>> flavor[13:15]
            ''

            In this example, the first line gets the slice from the beginning of the
            string up to but not including the fourteenth character. The string
            assigned to flavor has a length of seven, so you might expect Python
            to throw an error. Instead, it ignores any nonexistent indices and re-
            turns the entire string "fig pie".

            The third line shows what happens when you try to get a slice in which
            the entire range is out of bounds. flavor[13:15] attempts to get the
            thirteenth and fourteenth characters, which don’t exist. Instead of
            raising an error, Python returns the empty string ("").





                                                                          75
   71   72   73   74   75   76   77   78   79   80   81