Page 89 -
P. 89

smart data


           Python data is smart


           The more code you write, the more you will find that you need to do the
           same kind of things to the data in your variables all the time. To prevent
           you from having to create the same code over and over, programming
           languages provide built-in functionality to help you avoid writing
           unnecessary code. Python data is smart: it can do things.
           Let’s look at an example.
           Imagine you have a piece of text in a variable that you want to display in
           uppercase (all CAPITAL letters):




                     msg = "Monster truck rally. 4pm. Monday."


          You could write code that read through each character in the string and
           printed out the matching uppercase letter. But if you’re programming in a
           language like Python, you can do this:




                    The dot means
                   “call the method on"       “upper()" is a string method.
                    the specified variable.


                             print(msg.upper())
                                                                                 Here’s what gets
                                                                                displayed, the value of
                             MONSTER TRUCK RALLY. 4PM. MONDAY.                  the “msg" variable in
                                                                                UPPERCASE.



           But what does msg.upper() mean?
           Well, msg is the string containing our piece of text. The .upper() that
           follows it is called a string method. A method is just an instruction for the
           string. When you call msg.upper(), you are telling the string to give
           you an UPPERCASE version of its data.
           But is there a string method that can help you search
           for a substring within a string object?






           54    Chapter 2
   84   85   86   87   88   89   90   91   92   93   94