Python string formatting: reference one argument multiple times
Solution 1:
"{0} {1} {1}".format("foo", "bar")
Solution 2:
"%(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 ;)
Solution 3:
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.