[CentralOH] Python % Formatting

Mark Erbaugh mark at microenh.com
Thu Dec 6 15:04:55 CET 2007


I would like to be able to expand Python's % string formatting to
include 'conditional' separators. My idea is that the text separating
two fields would only be included in the output string if there were
actually text on both sides of it.

For example, consider formatting a person's name. The name consists of
first, middle and last parts.  Assume the data is supplied in a
dictionary:

name = {'first': 'Mark', 'middle' : 'E.', 'last': 'Erbaugh'}

I can create an string of the name using:

'%(first)s %(middle)s %(last)s' % name ==> 'Mark E. Erbaugh'

Using the same data, I can create a name in the last, first format:

'%(last)s, %(first)s %(middle)s' % name ==> 'Erbaugh, Mark E.'

Suppose I have a person with no middle name. The resulting string would
have two spaces between the first and last name. Similarly, if the
person only has one name and it was stored in the 'last' field, it would
print with two leading spaces. I'd like the routine to be able to get
rid of these extraneous spaces.

Another use for this would be in formatting of mailing addresses. Some
addresses may have two address lines, some only the first.

addr = {'line1' : '123 XYZ Street', 'line2' : 'Apt 12'}

'%(line1)s\n%(line2)s' % addr

If line2 is blank it would be nice to eliminate the separating '\n', so
there would be no blank line in the address.

Mark





More information about the CentralOH mailing list