[Tutor] Defining a "format string"

Alan Gauld alan.gauld at btinternet.com
Sun Jun 26 18:15:14 CEST 2011


"Lisi" <lisi.reisz at gmail.com> wrote

> So, if I have now understood correctly, a format string is a string 
> containing
> at least one variable, and the variable(s) is/are preceded by the % 
> symbol.
> Yes???

Umm, nearly...
The format string contains format specifiers. They are not variables.
The specifiers define the type of data to be inserted into the string
as well as how the data will be formatted - hence the name.

So you can specify how many decimal places for a float, whether
numbers have leadig zeros, whether text is righ or left justified and 
more.
(The new format specificiers in Python v3 are even more powerful)

You can store a format string as a variable (as Steven demonstrated)
and use it in several places to ensure consistent output. You can
swupply the values to the format string by using variables (again,
as Steven demonstrated). But they can also be literal values (as
Noah demonstrated) so that no variables are used at all.

You can also label format specifiers and then pass in a dictionary
of values where the labels are the keys into the dictionary. This is
very useful where the same values are used several times in a long
string. For example you could have a set of standard letter templates
into which you insert recipient data. You can then store the recipents
as a list of dictionaries ( or even a dictionary of dictionaries!) and 
then
do stuff like:

for recipient in customer_list:
     print offer_letter % recipient

Here is a small example:

>>> p = {'name':'Alan', 'balance': 100, 'duration': 300}
>>> msg = "\nHello %(name)s,\nWe haven't heard from you for 
>>> %(duration)s days.\nIf you come back we'll give you $10 off your 
>>> next order."
>>> print msg % p

Hello Alan,
We haven't heard from you for 300 days.
If you come back we'll give you $10 off your next order.
>>>

Notice I didn't need to use all the fields of p. The format
operation only extracted the fields named in the format
string.

It will even work with classes if you implement a __getitem__()
method

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list