String formatting with %s

D

Donn Ingle

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:A and B

Now, is there something quick like: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
 
M

Mel

Donn said:
> Now, is there something quick like:
B and A

?

GNU glibc printf accepts a format string:

printf ("%2$s and %1$s", "A", "B");

to produce what you want -- but not Python, AFAIK.


Mel.
 
M

MRAB

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" )

A and B

Now, is there something quick like:>>> s = "%s/2 and %s/1" % ( "A", "B" )

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'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,190
Latest member
ClayE7480

Latest Threads

Top