【问题标题】:Why is printing out with format throwing NoneType error? [closed]为什么打印出格式会抛出 NoneType 错误? [关闭]
【发布时间】:2019-11-23 18:32:44
【问题描述】:
account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = 0.00
for key in account_balance:
    total += float(account_balance[key])

然后这个:

print("TOTAL: {0}").format(str(total))

抛出一个错误:

AttributeError: 'NoneType' 对象没有属性 'format'

...为什么?

【问题讨论】:

  • 您在print() 上调用.format(),而不是在字符串上。我建议使用 f-strings。
  • 最终答案是:print("TOTAL: {0}".format(str(total))) 与 print("TOTAL: {0}").format(str(total))

标签: python error-handling


【解决方案1】:

应该是:

print("TOTAL: {0}".format(str(total)))

您的原始代码试图将.format() 方法调用到print 函数的返回值。因为它总是None,所以你会得到一个AttributeError

如果您使用的是 Python >=3.6,我建议您为此使用 f-strings。它们使用起来非常棒,并且会让字符串格式化成为一种乐趣:

print(f"TOTAL: {total}")

还有这段代码:

account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = 0.00
for key in account_balance:
    total += float(account_balance[key])

可以通过使用sumgenerator expression 来简化并提高效率:

total = sum(float(value) for value in account_balance.values())

或者使用summap

total = sum(map(float, account_balance.values()))

所有这些都可以使您的代码美观且易于阅读:

account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = sum(float(value) for value in account_balance.values())
print(f"TOTAL: {total}")

输出:

TOTAL: 206.56

【讨论】:

  • 为什么不account_balance.values()
  • @SayanipDutta 是的,我自己也意识到了这一点,已修复:)
【解决方案2】:

您可能想试试这个:
account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'} total = 0.00 for key in account_balance: total += float(account_balance[key])

print(total)
206.56

【讨论】:

    猜你喜欢
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多