Python 我该如何解决这个“TypeError: ‘str’ object is not callable”错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16873727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I fix this "TypeError: 'str' object is not callable" error?
提问by user2443381
I'm creating a basic program that will use a GUI to get a price of an item, then take 10% off of the price if the initial price is less than 10, or take 20% off of the price if the initial price is greater than ten:
我正在创建一个基本程序,该程序将使用 GUI 来获取商品的价格,如果初始价格低于 10,则减价 10%,如果初始价格为 20%,则减价 20%大于十:
import easygui
price=easygui.enterbox("What is the price of the item?")
if float(price) < 10:
easygui.msgbox("Your new price is: $"(float(price) * 0.1))
elif float(price) > 10:
easygui.msgbox("Your new price is: $"(float(price) * 0.2))
I keep getting this error though:
我不断收到此错误:
easygui.msgbox("Your new price is: $"(float(price) * 0.1))
TypeError: 'str' object is not callable`
Why am I getting this error?
为什么我收到这个错误?
采纳答案by Martijn Pieters
You are trying to use the string as a function:
您正在尝试将字符串用作函数:
"Your new price is: $"(float(price) * 0.1)
Because there is nothing between the string literal and the (..)parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:
因为字符串文字和(..)括号之间没有任何内容,Python 将其解释为将字符串视为可调用对象并使用一个参数调用它的指令:
>>> "Hello World!"(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Seems you forgot to concatenate (and call str()):
似乎您忘记连接(并调用str()):
easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))
The next line needs fixing as well:
下一行也需要修复:
easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))
Alternatively, use string formatting with str.format():
或者,使用字符串格式化str.format():
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))
where {:02.2f}will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.
where{:02.2f}将被您的价格计算替换,将浮点值格式化为带有 2 个小数的值。

