13 3.1. Using Python as a Calculator Python Tutorial, Release 3.9.5 (continued from previous page) Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to$_{s}$: Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced. One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n , for example: The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j , respectively. For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of$_{word[1:3]}$ is 2. Attempting to use an index that is too large will result in an error: However, out of range slice indexes are handled gracefully when used for slicing: Python strings cannot be changed — they are immutable . Therefore, assigning to an indexed position in the string results in an error: >>> word[0] ='J' Traceback (most recent call last): File "<stdin>" , line1, in <module> TypeError: 'str' object does not support item assignment >>> word[2:]='py' Traceback (most recent call last): File "<stdin>" , line1, in <module> TypeError: 'str' object does not support item assignment >>> word[4:42 ] 'on' >>> word[42 :] '' >>> word[42 ] # the word only has 6 characters Traceback (most recent call last): File "<stdin>" , line1, in <module> IndexError: string index out of range +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 >>> word[:2] # character from the beginning to position 2 (excluded) 'Py' >>> word[4:] # characters from position 4 (included) to the end 'on' >>> word[-2:] # characters from the second-last (included) to the end 'on' >>> word[:2] +word[2:] 'Python' >>> word[:4] +word[4:] 'Python' >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho'