Module: Formating not calculating

Objectives

a If all calculations are finished, print is often used to present all values as a string. Beside the old %s-Operator in Python 3.x a new function is available. Examples are showing some nice solutions.

Instructions

Tasks:
  1. Change the examples presented in the old as in the new notation.

  2. Print a list, as it is listed on a sales slip.

  3. Look at the examples in the Python documentation at:

    http://docs.python.org/2/library/string.html#format-examples

String formating with the Moduluo-Operator %

Principles to the old version

  • The % sign is a wildcard, followed by a letter indicating the data type.
  • Examples: %s, %d, %f, %2d, %2.3f
  • The number after the percent sign specifies the precision to be used for output.
  • The last % sign initiates the handover of parmaeter(s) to be used for the placeholder.
  • The number of parameters (list, tuple) must match the number of placeholders.

Special case: Dictionary as parameter

  • If the parameter is a dictionary, then the wildcard must matching the names (keys) of the dictinary.

Example 1

for i in range(1,11):
  print("%s * %s = %s" % (i,10,i*10))

Example 2

print("The %s f%sx j%ss" % ("brown","o","ump"))

Example 3

# create a dictionary...

mushrooms = {} # empty dictionary
mushrooms['cep'] = ['eatable x times', "mixed forest", "Boletus edulis"]
mushrooms['fly amanita'] = ["eatable once", "coniferous forest", "Amanita muscaria"]
mushrooms['bay bolete'] = ["eatable x times", "mixed forest", "Boletus badius"]
mushrooms['Coprinus'] = ['eatable x times', "meadow", "Coprinus"]

# print the content:

print('''Pretty print dictionary of mushrooms:\n ''')

for i in mushrooms.keys():
    print("""kind = %s, eatable = %s, be found = %s; """.format(i,
                                                                mushrooms[i][0],
                                                                mushrooms[i][1]))

Example 4

adress = {"firstnamename": "Robin",
          "lastname": "Hood",
          "location": "Sharewood Forest",
          "mark": "Bow & Arrow"}

print("""
         Wanted %(lastname)s, %(firstname)s
         special mark %(mark)s
         lives in %(location)s
      """ % (adress)

String formating with format()

This new method was discussed in PEP 3101 and is available since Python version 2.7.

Principles to the new version

  • placehoder is a pair of curly braces
  • the parameter are placed in the format method

The following examples repeat the old examples above and should the cause the same result.

Example 1

for i in range(1,11):
  print('{} * {} = {}'.format(i,10,i*10))

The same example, but more table like:

for i in range(1,11):
  print('{:2d} * {:2d} = {:3d}'.format(i,10,i*10))
x = 10
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
print("The {} f{}x j{}s".format("brown","o","ump"))

Example 3

# create a dictionary...

mushrooms = {} # empty dictionary
mushrooms['cep'] = ['eatable x times', "mixed forest", "Boletus edulis"]
mushrooms['fly amanita'] = ["eatable once", "coniferous forest", "Amanita muscaria"]
mushrooms['bay bolete'] = ["eatable x times", "mixed forest", "Boletus badius"]
mushrooms['Coprinus'] = ['eatable x times', "meadow", "Coprinus"]

# print the content:

print('''Pretty print dictionary of mushrooms:\n ''')

for i in mushrooms.keys():
    print("""kind = {}, eatable = {}, be found = {}; """.format(i,
                                                                mushrooms[i][0],
                                                                mushrooms[i][1]))

Excample 4

adress = {"firstnamename": "Robin",
          "lastname": "Hood",
          "location": "Sharewood Forest",
          "mark": "Bow & Arrow"}
print("""
         Wanted {lastname}, {firstname}
         special mark {mark}
         lives in {location}
      """ % (**adress)

Example 5

A little collection fo exotic versions...

>>> name ="Peter"
>>> "{!r:>10}".format(name)
"   'Peter'"

>>> '{:x>42}'.format(name)
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxPeter'