Python 字符串格式:多次引用一个参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4709310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python string formatting: reference one argument multiple times
提问by Nick Heiner
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.)
替换令牌必须是什么?(我知道我上面的例子是不正确的;我只是想表达我的目标。)
采纳答案by mouad
"{0} {1} {1}".format("foo", "bar")
回答by Serdar Dalgic
"%(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 ;)
是另一个真实但冗长的答案。只是为了向您展示有关该问题的另一种观点;)
回答by John Kugelman
Python 3 has exactly that syntax, except the %operator is now the formatmethod. str.formathas also been added to Python 2.6+ to smooth the transition to Python 3. See format string syntaxfor more details.
Python 3 具有完全相同的语法,除了%操作符现在是format方法。str.format也已添加到 Python 2.6+ 以平滑过渡到 Python 3。有关更多详细信息,请参阅格式字符串语法。
>>> '{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.
但是,在旧版本的 Python 中不能使用元组来完成。您可以使用括在括号中的映射键来接近。使用映射键,格式值必须作为字典而不是元组传入。
>>> '%(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.
当正确的参数是字典(或其他映射类型)时,字符串中的格式必须在该字典中包含一个带括号的映射键,该键紧接在 '%' 字符之后插入。映射键从映射中选择要格式化的值。

