[CentralOH] Python % Formatting

Brandon Mintern bmintern at gmail.com
Thu Dec 6 23:24:35 CET 2007


Upon defining my formatter operation, I realized it had a couple
shortcomings that I have fixed in this new version. It now takes
"format" as any iterable, and keys can include types such as int
(instead of just str as before). Here's the new version.

def formatter(items, format):
    """
    formatter(items, format)
    A special purpose formatting function which takes items as a dictionary
    and format as an iterable where the first element in format is a
    delimiter and the rest of the elements are either keys into items or
    another iterable with the same structure.
    The return value is best illustrated with some examples:
    d = {'a': 'r', 'b': 's', 'c': 't'}
    formatter(d, (' ', 'a', 'b', 'c'))                          # 'r s t'
    formatter(d, (' ', 'a', 'b', 'd', 'c'))                     # 'r s t'
    formatter(d, (' ', 'a', (';', 'b', 'c')))                   # 'r s;t'
    formatter(d, (' ', 'a', (';', 'b', 'c', (',', 'd', 'e'))))  # 'r s;t'
    """
    it = iter(format)
    try:
        delim = it.next()
        assert delim is str
    except (StopIteration, AssertionError):
        raise ValueError("1st element of format iterable"
                         " must be delimiter of type str")
    strings = []
    for x in it:
        if type(x) is not str:
            try:
                fmt_str = formatter(items, x)
                if fmt_str: # if result is an empty string, ignore it
                    strings.append(fmt_str)
                continue
            except TypeError: # x must a key of another type, like int
                pass
        if x in items:
            strings.append(items[x])
    return delim.join(strings)


More information about the CentralOH mailing list