返回要提供给 string.format() 的参数元组
目前,我正在尝试在 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))
当我尝试运行此代码时,编译器给出 IndexError:元组索引超出范围。
我应该如何构造返回值以将其作为参数传递给 .format()
?
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:
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()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你只缺少星星:D
You are missing only the star :D
自 Python 2.6 中引入以来,格式优先于 % 运算符: http ://docs.python.org/2/library/stdtypes.html#str.format
只需使用 * 解压元组 - 或使用 ** 的字典 - 而不是修改格式字符串。
Format is preferred over the % operator, as of its introduction in 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.
这尝试使用“卡片”作为单一格式输入来打印,而不是卡片的内容。
尝试类似的方法:
This attempts to use "cards" as single format input to print, not the contents of cards.
Try something like: