String formatting¶
We have talked about strings before, and you know that it is possible to construct strings containing values, e.g.
'x=' + str(43.2) + ', y=' + str(1./3.)
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:
'{0} {1} {2}'.format(1./3., 2./7., 2.)
In the above example, the 0
, 1
, and 2
refer to the position of the argument in the parentheses, so one could also do:
'The quantity {0} that could also be called {0} {1}'.format(1./3., 2./7.)
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:
'{0:10.3f}'.format(1./3.)
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):
'{0:10d}'.format(4)
There are a number of options for string formatting - for instance, one can add leading zeros:
'{0:010d}'.format(4)
or align to the left:
'{0:<10d}'.format(4)
Instead of using 0
, 1
, etc. it is also possible to pass the values by name:
'{day:02d}'.format(day=3)
Here is an example of string formatting for a date:
'{year:04d}{month:02d}{day:02d}'.format(year=2013, month=7, day=8)
An even more concise form to write this is called an "f-string" , which combines everything into one string.
For f-strings the object names are put directly into the string:
year=2013
month=7
day=8
f'{year:04d}{month:02d}{day:02d}'
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
:
# 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:
# your solution here