[CentralOH] Python % Formatting

Greg Singer gacsinger at gmail.com
Thu Dec 6 17:37:30 CET 2007


On Dec 6, 2007 9:04 AM, Mark Erbaugh <mark at microenh.com> wrote:
> 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.

It's a neat idea, but it's easy enough to pass the resulting string
through a filter to remove extraneous whitespace:

import re
filter=lambda s:re.sub(r'(\s){2,}',r'\1',s)

#original example
name = {'first': 'Mark', 'middle' : 'E.', 'last': 'Erbaugh'}
print filter('%(first)s %(middle)s %(last)s' % name)
# ==> Mark E. Erbaugh

#no middle name
name = {'first': 'Mark', 'middle' : '', 'last': 'Erbaugh'}
print filter('%(first)s %(middle)s %(last)s' % name)
# ==> Mark Erbaugh

 - Greg


More information about the CentralOH mailing list