python 返回要馈送到 string.format() 的参数元组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/539066/
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
Return a tuple of arguments to be fed to string.format()
提问by Yes - that Jake.
Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter, and then pass them to the string method. My code looks something like this:
目前,我正在尝试在 Python 中获取一个方法来返回零、一个或两个字符串的列表以插入字符串格式化程序,然后将它们传递给字符串方法。我的代码看起来像这样:
class PairEvaluator(HandEvaluator):
def returnArbitrary(self):
return ('ace', 'king')
pe = PairEvaluator()
cards = pe.returnArbitrary()
print('Two pair, {0}s and {1}s'.format(cards))
When I try to run this code, the compiler gives an IndexError: tuple index out of range.
How should I structure my return value to pass it as an argument to .format()
?
当我尝试运行此代码时,编译器给出一个 IndexError: tuple index out of range。
我应该如何构造我的返回值以将其作为参数传递给.format()
?
回答by Bartosz Radaczyński
print('Two pair, {0}s and {1}s'.format(*cards))
You are missing only the star :D
你只缺少明星 :D
回答by trojjer
Format is preferred over the % operator, as of its introduction in Python 2.6: http://docs.python.org/2/library/stdtypes.html#str.format
从 Python 2.6 中的介绍开始,格式优于 % 运算符:http: //docs.python.org/2/library/stdtypes.html#str.format
It's also a lot simpler just to unpack the tuple with * -- or a dict with ** -- rather than modify the format string.
只需使用 * 或带有 ** 的 dict 解压缩元组,而不是修改格式字符串也简单得多。
回答by Andrew Grant
This attempts to use "cards" as single format input to print, not the contents of cards.
这试图使用“卡片”作为单一格式的输入来打印,而不是卡片的内容。
Try something like:
尝试类似:
print('Two pair, %ss and %ss' % cards)