John Lam 1997 — 2026

Emulating String.Format() semantics in Python

We’re rather spoiled with positional identifiers in String.Format(). It’s only when you go back to old-school printf style formatting that you realize this. I really wanted that feature back in Python, so I rolled my own today. It was surprisingly easy, and today’s Python program taught me a bunch of things about Python, specifically:

  1. tuples, lists of tuples, tuples as return values, and tuples in for statements
  2. using eval to compile a custom function on the fly
  3. marveling at how tuples allow both (a,b,) AND (a,b)

Here is today’s adventure in Python:

import re

url = r'\b((http|ftp|mailto):[\w;/#~:.?+=&%@!\-] +?)(?=[.:?\-]*[^\w;/#~:.?+=&%@!\-]|$)'

inline_args = [\
    (r'\@(.*?)\@', r'$1'),
    (r'\_(.*?)\_', r'<emph>$1</emph>'),\
    (r'\*(.*?)\*', r'<strong>$1</strong>'),\
    (r'\"(.*?)\":(%s)' % url, r'<a href="$2">$1</a>')\
]

re_parseTemplate = re.compile(r'\$(\d+)', re.IGNORECASE)

class parser:

    def __init__(self):
        self.templates = list()
        for (regex, template) in inline_args:
            self.templates.append(templateExpression(regex, template))

    def parse(self, str):
        for template in self.templates:
            str = template.expand(str)
        return str

class templateExpression:

    def generateTemplateExpression(self, template):
        templateExpr    = re_parseTemplate.sub(r'%s', template)
        argIndices      = re_parseTemplate.findall(template)

        expr = "'" + templateExpr + "' % ("
        for n in argIndices:
            expr += 'mo.group(%s), ' % n
        expr += ')'
        return expr

    def __init__(self, regex, template):
        self.re_parser = re.compile(regex, re.IGNORECASE)
        expr = self.generateTemplateExpression(template)
        self.lfunc = eval(r'lambda mo : ' + expr)

    def expand(self, str):
        return self.re_parser.sub(self.lfunc, str)

p = parser()
print p.parse(r'this is a "url":http://www.iunknown.com @that@ i _want_ to *test*')
5 archived reader comments

Chris Tavares (2004-09-22)

I hate to tell you this, but there’s an even easier way. While python doesn’t have positional replacements, it does have NAMED replacements.

You’re already aware of the ‘%’ operator when applied to strings. In addition to using tuples as the right hand side of the expression, you can also use a dictionary. In your substitution, instead of saying ‘%s’, say ‘%(name)s’, and python will use name as the key in the dictionary.

For example:

“Hello %(name)s, isn’t it a %(description)s day?” % { “name” : “Chris”, “description” : “wonderful” } “Hello Chris, isn’t it a wonderful day?”

So your regex stuff, while very educational, is kinda overkill. But that happens to everyone when learning Python.

Gordon Weakliem (2004-09-22)

One other trick you can use to get positional formatting is the locals() function, e.g.

foo = 1 bar = 2 print “%(foo)d %(bar)d” % locals() 1 2 print “%(bar)d %(foo)d %(bar)s” % locals() 2 1 2

John Lam (2004-09-22)

Gordon: thanks for the @locals()@ tip.

Chris: I’m not sure that your solution solves my problem - which isn’t purely just about positional identifiers. I’m trying to build a simple templating engine that maps regex match groups to template parameters.

Positional identifiers lets me keep the syntax simple. Even if I did use named identifiers, I don’t think I could avoid my regex trick since I need to correlate parameters in two different strings.

Or am I missing something here?

**** (2004-09-22)

Ahh, I see your actual task is a lot more than just positional replacement. I’d still tend towards using named groups in the regex (using the (?…) syntax) and named replacement positions in the string template, because I find they make life easier the long run.

I’ll have to cogitate a little more before I post another reponse.

Chris Tavares (2004-09-22)

Argh, that last one was me. And the named group syntax in regexes is actually (?P…).