String formatting with %s

MRAB google at mrabarnett.plus.com
Sun Dec 2 13:49:18 EST 2007


On Dec 2, 1:35 pm, Donn Ingle <donn.in... at gmail.com> wrote:
> Hi,
>  I'm sure I one read somewhere that there is a simple way to set the order
> of replacements withing a string *without* using a dictionary.
>
> What I mean is:>>> s = "%s and %s" % ( "A", "B" )
> >>> print s
>
> A and B
>
> Now, is there something quick like:>>> s = "%s/2 and %s/1" % ( "A", "B" )
> >>> print s
>
> B and A
>
> ?
>
> I know it can be done with a dict:
> d = { "one" : "A", "two" : "B"  }
> s = "%(two)s and %(one)s" % d
>
> \d

One quick solution is to write a function for it:

def format(template, values):
    import re
    # Collect the indexes from the template.
    order = map(int, re.findall(r'%\[(\d+)\]', template))
    # Remove the indexes from the template.
    template = re.sub(r'(?<=%)\[(\d+)\]', '', template)
    # Create a tuple containing the values in the correct positions.
    values = tuple(values[index] for index in order)
    return template % values

>>> format("%[0]s and %[1]s", ("A", "B"))
'A and B'
>>> format("%[1]s and %[0]s", ("A", "B"))
'B and A'



More information about the Python-list mailing list