Page 215 -
P. 215

string formats


           Use strings to format strings


           Many programs need to create strings with particular pieces of data
           at particular places, so most computer languages try to make life
           easier for you by letting you use string formats.
           The best way to understand string formats is with an example. Open
           up the Python Shell and type in this:           The first value will
                                                           be inserted as a             The second value will be
                                                           5-character number.           inserted as a string.


                         >>> print("There are %5d %s available" % (17, "donuts"))


                         There are    17 donuts available
                                                                             The string-formatting
                         The number has extra spaces                         operator
                         added at the front, to make
                         sure it takes up the required 5
                         characters.
                                                                                  OK, this string is
           When Python sees a string followed by a percentage (%) symbol,         followed by a % symbol.
           it knows that it needs to consider the string as a string format.      So... I‛ll need to replace
           The values that follow the % operator are going to be inserted into    %5d with the number 17,
           the formatted string in the order specified, one value at a time.      and %s with the string
           Wherever Python finds a % inside the string, it knows to insert a      “donuts”.
           value.
                A number format
                specification  %5d



           When Python sees this, it will insert the value 17 as a 5-character
           whole number—that’s because the “d” type specifier tells Python
           to print the number as a decimal. Because 17 is not 5-characters
           long, Python will left-pad it with 3 extra spaces at the front to make
           it the correct length.
                  A string format   %s
                  specification


          This symbol tells Python to insert the value “donuts” as a string.
          As you are not specifying a length here, the string is inserted as is.


          These are just two examples of how to format
          values in a string. There are lots more.


           180    Chapter 6
   210   211   212   213   214   215   216   217   218   219   220