String formatting

We have talked about strings before, and you know that it is possible to construct strings containing values, e.g.

In [1]:
'x=' + str(43.2) + ', y=' + str(1./3.)
Out[1]:
'x=43.2, y=0.3333333333333333'

However, one may want to format the values in more detail, for example forcing values to be a certain length, or have a certain number of decimal places. This is called string formatting.

The syntax for formatting strings looks like this:

In [2]:
"{0} {1} {2}".format(1./3., 2./7., 2.)
Out[2]:
'0.3333333333333333 0.2857142857142857 2.0'

In the above example, the 0, 1, and 2 refer to the position of the argument in the parentheses, so one could also do:

In [3]:
"{0} {0} {1}".format(1./3., 2./7.)
Out[3]:
'0.3333333333333333 0.3333333333333333 0.2857142857142857'

By default, the value looks the same as if one had used str(), but you can also specify the format and number of decimal places:

In [4]:
"{0:10.3f}".format(1./3.)
Out[4]:
'     0.333'

The f stands for floating-point, the 10 is the total length of the string, and the 3 is the nuber of decimal places.

We can do something similar for integers (without the number of decimal places):

In [5]:
"{0:10d}".format(4)
Out[5]:
'         4'

There are a number of options for string formatting - for instance, one can add leading zeros:

In [6]:
"{0:010d}".format(4)
Out[6]:
'0000000004'

or align to the left:

In [7]:
"{0:<10d}".format(4)
Out[7]:
'4         '

Instead of using 0, 1, etc. it is also possible to pass the values by name:

In [8]:
"{day:02d}".format(day=3)
Out[8]:
'03'

Here is an example of string formatting for a date:

In [9]:
"{year:04d}{month:02d}{day:02d}".format(year=2013, month=7, day=8)
Out[9]:
'20130708'

Exercise 1

Write a function that takes year, month, day, hour, minutes, and seconds and converts them to a string with format 2006-03-22 13:12:55:

In [10]:
# your solution here

Exercise 2

Write a function that takes a string like 2006-03-22 13:12:55 and return the year, month, day, hour, minutes, and seconds as integers:

In [11]:
# your solution here