python元组索引超出范围_“元组索引超出范围”错误?

在animalFormat中,替换:{1}

有:

^{pr2}$

这个改变必须在两个地方进行。在

由于使用关键字为format提供参数,因此1没有可引用的内容。在

更简单的例子

请注意这一点:>>> d = {'a':1, 'b':2}

>>> 'Twice {a} is {b}'.format(**d)

'Twice 1 is 2'

但这行不通:>>> 'Twice {1} is {b}'.format(**d)

Traceback (most recent call last):

File "", line 1, in

IndexError: tuple index out of range

如果为format提供关键字参数,则1没有可引用的内容。在

可以同时提供位置参数和关键字参数。例如:>>> 'Twice {1} is {b}'.format('Arg0', 'ArgOne', **d)

'Twice ArgOne is 2'

完成工作代码animal = input("Enter any LARGE animal: ")

smallAnimal = input("Enter any SMALL animal: ")

weapon = input("Enter a sharp weapon: ")

def createDictionary():

storyDict = dict()

storyDict['animal'] = animal

storyDict['smallAnimal'] = smallAnimal

storyDict['weapon'] = weapon

return storyDict

def main():

dictionary = createDictionary()

animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there was. And one day, a wild {smallAnimal} had

stepped on the {animal}'s foot. At that moment, the {smallAnimal} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the_

{smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.

The End."""

withSubstitutions = animalFormat.format(**dictionary)

print(withSubstitutions)

main()

样本运行:Enter any LARGE animal: Lion

Enter any SMALL animal: Mouse

Enter a sharp weapon: knife

Once upon a time, there was a very, very large Lion. This Lion was the meanest, baddest, most gruesome Lion there was. And one day, a wild Mouse had

stepped on the Lion's foot. At that moment, the Mouse knew it had messed up. This made the Lion angry, so he took a knife and STABBED the

Mousewith it! The Mouse squirmed and fought to get out, but it was no match for the Lion with a knife.

The End.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值