Page 305 - Computer Science Class 11 With Functions
P. 305

>>> print(greet[–5], greet[–4], greet[–3], greet[–2], greet[–1])
                 hello

                                       greet

                                       Non-negative     0       1      2      3       4
                                          indices

                                                        h       e      l       l      o

                                         Negative      -5      -4      -3     -2     -1
                                          indices
                                                   Fig 12.1 String greet indexing


            12.1.2 Strings are Immutable!
            Strings in Python are immutable, i.e., a string cannot be modified. An attempt to modify a string will yield an error.
            For instance, an attempt to replace the character at index 1 ('a') with 'o' in the string 'Kamal' results in an
            error:
             >>> name = 'Kamal'
             >>> name[1] = 'o'
                 Traceback (most recent call last):
                     File "<pyshell#55>", line 1, in <module>
                         name[1] = 'o'
                 TypeError: 'str' object does not support item assignment


                   Strings in Python are immutable, i.e., a string cannot be modified. An attempt to modify a string will yield an error.


            However, it is perfectly fine to create a new string and assign it to an existing variable. For example,

             >>> name = 'Kamal'
             >>> name
                 'Kamal'
             >>> name = 'Komal'
             >>> name
                 'Komal'
            12.1.3 Invalid Indices

            An index outside the valid range of indices is said to be out of range. An attempt to access a component of a string
            using an index outside of the valid range of indices will result in an error. For instance, the set of valid indices for data
            stored in greet ('hello') are 0, 1, 2, 3, and 4; and -5, -4, -3, -2, and -1. Thus, accessing index 7,
            which is outside these ranges, will yield an error as shown below:

             >>> greet[7]
                 Traceback (most recent call last):
                     File "<pyshell#7>", line 1, in <module>
                         greet[7]
                 IndexError: string index out of range

                   Set of valid indexes for accessing string characters includes [0, len(string)-1] and [-len(string), -1]. An attempt to
                   access a component of a string using an index outside of the valid range of indices will result in an error.







                                                                                                       Strings   303
   300   301   302   303   304   305   306   307   308   309   310