TypeError:无法隐式地将'float'对象转换为str

时间:2013-10-29 17:11:12

标签: python

TypeError:无法将'float'对象隐式转换为str

print("\nYou will make {:.2f}".format(score * live - BIN))

3 个答案:

答案 0 :(得分:1)

您无法隐式将float转换为str。 :)

您需要将数字部分包装在str中。或者,更好的是,使用字符串格式:

print("\nYou will get {}".format((score + power) - BIN))

答案 1 :(得分:1)

您的(score + power)表达式会产生float值,并且您尝试将其连接到带有+的字符串。你不能这样做,因为这需要将值隐式转换为字符串。

打印时使用逗号:

print("\nYou will get", (score + power) - BIN)

并让print()函数为您转换,或使用字符串格式(这使您可以更好地控制浮点格式的方式):

print("\nYou will get {:.2f}".format((score + power) - BIN))

或者将其应用于整个程序:

BIN = float(input("\nEnter the buy-it-now price of the item: £"))
Postage = float(input("\nEnter the shipping & handling cost of the item: £"))

eBayFee = (BIN + Postage) / 10
PayPalFee = ((3.4 * BIN) / 100) + 0.2

print ("\nYou will be charged £{:.2f} eBay fees and £{:.2f} PayPal fees.".format(eBayFee, PayPalFee))

print("\nYou will make {:.2f}".format(BIN - eBayFee - PayPalFee))

请注意,这是现在将数字舍入到2个小数位的格式。我也纠正了这个公式;据推测,“利润”是“现在购买”价格减去eBay和PayPal费用,而不是合并的费用减去BIN。

答案 2 :(得分:0)

将float转换为字符串。

print("\nYou will get "+  str(score + power - BIN))