【问题标题】:I keep getting TypeError: 'str' object is not callable (python 2.7)我不断收到 TypeError: 'str' object is not callable (python 2.7)
【发布时间】:2015-04-20 07:48:52
【问题描述】:

伙计们,我是初学者,我正在尝试(有点失败)自学编程和编写代码,因此非常感谢您的帮助

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)

我不断收到错误:

 TypeError: 'str' object is not callable.

你们能告诉我我的代码有什么问题吗?对于初学者来说,如何知道要修复什么?

谢谢

【问题讨论】:

  • 哪一行导致错误?
  • 提供完整的回溯会更有帮助,其中包括有问题的行。

标签: python typeerror


【解决方案1】:

您在此处缺少 % 符号:

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

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

您可以使用format 方法:

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

【讨论】:

【解决方案2】:

你也可以这样做:

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

我只是更喜欢这种方式,因为它更明确,并且当您在字符串中替换太多参数以跟踪顺序时它很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 2023-03-18
    • 2021-06-06
    • 1970-01-01
    • 2021-02-03
    • 2021-04-21
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多