Page 260 - Computer Science Class 11 Without Functions
P. 260

greet


                      Non-negative        0            1           2            3            4
                      indices
                                          h            e            l            l           o
                      Negative           –5           –4           –3           –2          –1
                      indices
                                               Fig 11.1: String greet indexing

        11.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'
        11.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 include [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.


        11.1.4 Length of a String

        To find the length of a string, Python provides the built-in function len() which returns the length of a string. For
        example,





         258   Touchpad Computer Science-XI
   255   256   257   258   259   260   261   262   263   264   265