Page 109 - Computer - 8
P. 109

remaining characters are assigned an index number in sequence. For example, in the string “Python”
          the indexes assigned to various characters are:

                                                     P   y    t   h   o   n
                                                     0   1    2   3   4   5
          Python provides two ways for traversing a string:
            1.  Using a positive index: In this case, the index from left starts with 0.
            2.  Using a negative index: In this case, the index starts from the rightmost character with value -1.
                 The syntax to access a specific character in a string is
                        <  string name> [index]

            Lab Activity 5
                                                                                                   Experiential Learning
           To display the characters in a string using their indexes.

           1. Type the code as shown in the image in the Python Editor.













           2. Press the F5 key to execute the code. Sample output of the program is given below.



















          String Built-in Functions
          Python provides several built-in functions for working with strings. Some common string functions in
          Python are:
             •  len( ): It accepts a string as argument and returns its length. Its syntax is:
                len(<string>)
             •  lower( ): It accepts a string and converts all characters in it to lowercase. Its syntax is:

                 <string>.lower( )
             •  upper( ): It accepts a string and converts all characters in it to uppercase. Its syntax is:
                 <string>.upper( )
             •  capitalize( ): It accepts a string and returns it with the first character in uppercase, while all other
                characters are in lowercase. Its syntax is:
                 <string>.capitalize( )


                                                                                                             107
   104   105   106   107   108   109   110   111   112   113   114