开发者

Python string formatting: reference one argument multiple times

If I have a string like:

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

and I want:

"foo 开发者_JS百科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.)


"{0} {1} {1}".format("foo", "bar")


"%(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 ;)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜