[CentralOH] Python % Formatting

Brandon Mintern bmintern at gmail.com
Thu Dec 6 22:24:10 CET 2007


I think I would probably end up using the .join() operator for this
kind of thing.

def name_string (name):
    return ', '.join([name['last']] \
                     + filter(None, [' '.join([name[x] \
                                     for x in ('first', 'middle') \
                                     if x in name])]

>>> name_string(name)
'Erbaugh, Mark E.'
>>> del name['middle']
>>> name_string(name)
'Erbaugh, Mark'
>>> del name['first']
>>> name_string(name)
'Erbaugh'

Of course, that looks ugly, but it could be wrapped up in some kind of
function that would do it all for you:

def formatter(items, format):
    delim = format[0]
    strings = []
    for x in format[1:]:
        if type(x) is str:
            if x in items:
                strings.append(items[x])
        else:
            fmt_str = formatter(items, x)
            if fmt_str:
                strings.append(fmt_str)
    return delim.join(strings)

>>> name = {'first': 'Mark', 'middle' : 'E.', 'last': 'Erbaugh'}
>>> formatter(name, (', ', 'last', (' ', 'first', 'middle')))
'Erbaugh, Mark E.'
>>> del name['middle']
>>> formatter(name, (', ', 'last', (' ', 'first', 'middle')))
'Erbaugh, Mark'
>>> del name['first']
>>> formatter(name, (', ', 'last', (' ', 'first', 'middle')))
'Erbaugh'


More information about the CentralOH mailing list