Page 225 - Robotics and AI class 10
P. 225

Output:

             enter a name Susan
             Hello Susan Happy Learning


            Accessing the Elements of the String
            Each character in a string has a unique address called an index. The index number is always an integer which can
            be negative, zero or positive. A single character in a string can be accessed using an index number enclosed in
            square brackets([ ])

            There are two different ways of using the index number:
               • Forward Indexing: The index number begins with 0 till length-1 and we refer the elements from left to right.
               • Negative/Backward Indexing: The index number begins with -1 till-length and we refer to the elements from
              right to left. Negative indices are used when we want to access the characters of the string from right to left.
            Example:

            >>> S1="PYTHON"

                          Forward Indexing        0    1     2    3    4     5

                                                  P    Y     T    H    O     N

                                                 –6    –5   –4   –3    –2   –1        Backward Indexing


            Each element can be accessed by using:
              stringname[index number]

               print(S1[0])                                   P

               print(S1[3])                                   H
               print(S1[-3])                                  H

               print(S1[-1])                                  N
               print(S1)      #print complete string PYTHON

               print(S1[0],S1[4])                             P O
               print(S1[1+4])                                 N

               print(S1[10] )                                 IndexError: string index out of range
               print(S1[5.5])                                 TypeError: string indices must be integers


            String is Immutable
            Strings in Python are immutable. It means that the content of the string cannot be changed after it is created.
            For example:

            >>> s3 = "WELCOME"
            >>> s3[2]="!"
            TypeError: 's3' object does not support item assignment





                                                         Introduction to Data and Programming with Python  223
   220   221   222   223   224   225   226   227   228   229   230