Partial string formatting?

Jeff Epler jepler at unpythonic.net
Tue Jan 21 14:26:57 EST 2003


On Tue, Jan 21, 2003 at 04:18:55PM +0000, Gonçalo Rodrigues wrote:
> Hi,
> 
> Is there a simple way to do partial string formatting short of using
> RE's, e.g
> 
> <string> % <mapping>
> 
> where if a key is not present in <mapping> it just leaves it untouched?
> 
> I thought of subclassing dict to hand out a default item, which it would
> just be the requested key wrapped in %()s. Of course this only works if
> the format code is s but not with other format codes or even more
> complicated options.
> 
> Thanks in advance,
> G. Rodrigues
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I think the following function 'format(s, m)' will work.  I tested it a
little bit.

def format(s, d):
    chunks = s.split('%')
    out = [chunks[0]]
    for f in chunks[1:]:
        f = "%" + f
        try:
            out.append(f % d)
        except KeyError:
            out.append(f)

    return "".join(out)

ma = {'key1':'val1', 'key3':3}
print format("%(key1)s - %(key2)33s - %(key3)03d", ma)
#prints: "val1 - %(key2)33s - 003"

#jeff





More information about the Python-list mailing list