我一直得到TypeError:'str'对象不可调用(Python2.7)

2024-09-29 17:09:56 发布

您现在位置:Python中文网/ 问答频道 /正文

伙计们,我是一个初学者,我正在尝试(有点失败)自学编程和编写代码,所以你的帮助真的很感谢

favorite_foods = {'Armon' : 'wings',
'Dad' : 'kabob',
'Joe' : 'chinese',
'mom' : 'veggies',
'Das' : 'addas_polo',
'Rudy' : 'free_food',
'Nick' : 'hotnspicy',
'layla' : 'fries',
'Shaun' : 'sugar',
'Zareen' : 'cookie',
'Elahe' : 'hotdogs'}

print(favorite_foods)

print "Whose favorite food do you want to know"
person = raw_input()
fav = (favorite_foods[person])

print "%r favorite food is %s" (person, fav)

我一直收到错误:

^{pr2}$

你们能告诉我我的代码出了什么问题吗?对于初学者来说,该怎么解决?在

谢谢


Tags: 代码food编程favoritepersonprint初学者伙计
2条回答

此处缺少%sign:

print "%r favorite food is %s" % (person, fav)

在你的调用中你有:"%r favorite food is %s" (person, fav),在string对象后面有一个调用符号,这就是为什么它认为你试图将字符串作为函数“调用”。在

您可以使用format方法:

print "{person} favorite food is {food}".format(person=person, food=fav)

您也可以这样做:

print "{person} favorite food is {food}".format(person=person,food=fav)

我更喜欢这种方式,因为它更显式,当您有太多参数要替换为字符串来跟踪顺序时,它非常有用。在

相关问题 更多 >

    热门问题