Python string formatting: reference one argument multiple times

Question:

If I have a string like:

"{0} {1} {1}" % ("foo", "bar")

and I want:

"foo bar bar"

What do the replacement tokens have to be? (I know that my example above is incorrect; I’m just trying to express my goal.)

Asked By: Nick Heiner

||

Answers:

"{0} {1} {1}".format("foo", "bar")
Answered By: mouad
"%(foo)s %(foo)s %(bar)s" % { "foo" : "foo", "bar":"bar"}

is another true but long answer. Just to show you another viewpoint about the issue 😉

Answered By: Serdar Dalgic

Python 3 has exactly that syntax, except the % operator is now the format method. str.format has also been added to Python 2.6+ to smooth the transition to Python 3. See format string syntax for more details.

>>> '{0} {1} {1}' % ('foo', 'bar')
'foo bar bar'

It cannot be done with a tuple in older versions of Python, though. You can get close by using mapping keys enclosed in parentheses. With mapping keys the format values must be passed in as a dict instead of a tuple.

>>> '%(0)s %(1)s %(1)s' % {'0': 'foo', '1': 'bar'}
'foo bar bar'

From the Python manual:

When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the ‘%’ character. The mapping key selects the value to be formatted from the mapping.

Answered By: John Kugelman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.