【问题标题】:'NoneType' object has no attribute 'format' python string'NoneType' 对象没有属性 'format' python 字符串
【发布时间】:2020-06-23 19:47:27
【问题描述】:

我在 python 中编写了一个程序来查找复利(更像是复制的)。这个程序是用python 2编写的,我在最后一行.format(years)遇到了问题。

我需要知道我可以使用此代码做什么,以及如何在 Python 3 中正确编写它。还有最后一行中的 {} 部分。我应该将其更改为%s 吗?错误说:

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

我的代码如下所示:

# Estimated yearly interest

print ("How many years will you be saving ? ")
years = int(input("Enter the number of years : "))

print("How much money is currently in your account ? ")
principal = float(input("Enter current amount in account : "))

print("How much money do you plan on investing monthly ? ")
monthly_invest = float(input("Monthly invest : "))

print("What do you estimate the interest of this yearly investment would be ? ")
interest = (float(input("Enter the interest in decimal numbers (10% = 0.1) : ")))

print(' ')

monthly_invest = monthly_invest * 12
final_amount = 0

for i in range(0, years ):
    if final_amount == 0:
        final_amount = principal
    final_amount = (final_amount + monthly_invest) * (1 + interest)

print("This is how much money you will have after {} years:  ").format(years) + str(final_amount)

【问题讨论】:

  • 括号应该在末尾而不是字符串文字之后。此外,使用数学公式会更容易
  • 我想如果您查看 Python 文档,您会发现格式化字符串是一种完全可以接受的方法。 - docs.python.org/3/library/stdtypes.html#str.format.

标签: python string


【解决方案1】:

我觉得没有人推荐f-strings 有点遗憾。仅从 Python 3.6 开始提供,但它们非常强大,易于使用,并且在 PEP 498 中推荐了字符串格式化选项(除非我弄错了)。

如果您想认真对待 python 并与其他人合作,我真的建议您阅读最佳实践,在本例中为 f-strings。

使用 f-strings 的解决方案:

print(f"This is how much money you will have after {years} years: {final_amount}")

【讨论】:

  • 我是初学者,我还在学习基础知识,但感谢您的意见。这也有效。
【解决方案2】:

改变

print("This is how much money you will have after {} years:  ").format(years) + str(final_amount)

print("This is how much money you will have after {} years:  ".format(years)) + str(final_amount)

format()string 类的方法。您在 NoneTypeprint() 函数上使用它,因此出现错误。

【讨论】:

  • 当我把右括号放在最后时它可以工作。
【解决方案3】:

您可以像这样进行普通的字符串连接:

Print("This is how much money you will have after " + format(years) + " years: " +str(final_amount)

或者,如果您希望保持相同的格式,您可以这样做

print("This is how much money you will have after {} years: ".format(years) + str(final_amount))

【讨论】:

    【解决方案4】:

    一个非常基本的解决方案是将最后一行更改为:

    print("This is how much money you will have after {} years:".format(years), str(round(final_amount,2)))
    

    这对你有用

    【讨论】:

      【解决方案5】:

      你也可以使用Numpy's financial functions

      每月投资 1000 美元,为期 10 年,年利率为 4%:

      >>> import numpy as np
      >>> np.fv(.04/12, 10*12, -1000, 0)
      147249.8047254786
      

      初始本金为 100,000 美元:

      >>> np.fv(.04/12, 10*12, -1000, -100000)
      296333.07296730485
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-19
        • 2019-10-03
        • 2021-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多