String formatting with %s

James Matthews nytrokiss at gmail.com
Sun Dec 2 13:59:43 EST 2007


try to import printf using ctypes

On Dec 2, 2007 7:49 PM, MRAB <google at mrabarnett.plus.com> wrote:

> 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'
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071202/4cef1aa8/attachment.html>


More information about the Python-list mailing list