String formatting with %s

Tim Chase python.list at tim.thechases.com
Sun Dec 2 16:15:43 EST 2007


>  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

Well, if you're willing to cheat and use dictionary formatting
where your keys are the number you want (you've gotta have some
syntax for the index notation...why not reuse
dictionary-key/value syntax), you can do something like:

>>> number = lambda x: dict((str(i+1), v) for (i,v) in enumerate(x))
>>> "%(2)s and %(1)s" % number(["A", "B"])
'B and A'

If you don't mind zero-based indices, you can skip the "+1" bit.

-tkc





More information about the Python-list mailing list