Page 77 - Code & Click - 8
P. 77

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]
                                                                                                 Experiential Learning
              Lab Activity 4
             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( )
                                                                                                 Experiential Learning
              Lab Activity 5

             To display use of various string functions in Python.
             1. Type the code as shown in the image in the Python Editor.












                                                                                                                 75
   72   73   74   75   76   77   78   79   80   81   82