简体   繁体   中英

I keep getting TypeError: 'str' object is not callable (python 2.7)

Guys I'm a beginner and I'm trying (slightly failing) to teach myself programming and writing code so your help is really appreciated

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)

I keep getting the error:

 TypeError: 'str' object is not callable.

Can you guys tell me whats wrong with my code and how to, for beginners, know what to fix?

Thanks

You are missing % sign here:

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

In your call you have: "%r favorite food is %s" (person, fav) , and right after the string object there is a call sign, that's why it thinks that you tried to "call" a string as a function.

You can use the format method:

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

You can also do it like this:

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

I just prefer this way as it is more explicit and it is useful when you have too many parameters to replace in a string to keep track of the order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM