53

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

3 Answers 3

74
"{0} {1} {1}".format("foo", "bar")
Sign up to request clarification or add additional context in comments.

4 Comments

Interesting. Why does that work with "str".format(args) but not "str" % args?
@Rosarch: Because the {n} syntax only works for str.format(), not str.__mod__().
@Rosarch: i guess you have mixed the new way with the old way of formating because the old way don't use {} as a place holders :), but using the .format() is the new way of formating strings take a look at the pep 3101 for more detail : python.org/dev/peps/pep-3101
Could you pass more than one value to {0}? For example, if you have two instances of {0} in a string, but you want to pass two different strings for each one?
17
"%(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 ;)

1 Comment

+1 because I didn't know you could do this, and I prefer the readability
9

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.