【问题标题】:Not sure why I'm getting "TypeError: can only concatenate str (not "int") to str"不知道为什么我得到“TypeError:只能将str(而不是“int”)连接到str”
【发布时间】:2021-10-17 12:40:03
【问题描述】:

我有工作代码,但它每年都给我相同的Invest_amount(没有添加上一年的兴趣),所以我创建了一个Starting_balance 来尝试解决这个问题。

但是,现在它给了我这个错误信息:

TypeError: can only concatenate str (not "int") to str. But I put str in front of the value?

我的代码:

InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))
TotalInterestEarned = 0
for i in range(Years):
     InterestEarned = round(InvestAmount*(Rate/100),2)
     EndingBal = round(InvestAmount+InterestEarned , 2)
     Starting_balance = (InvestAmount + InterestEarned)
     print("Starting Balance: for year " + (i+1)+"$"+str(Starting_balance))    
     print("Ending balance: for year" +(i+1)+"$"+str(EndingBal))
     print("Total interest earned: for year" +(i+1)+"$"+str(InterestEarned))

【问题讨论】:

  • 很可能是在抱怨(i + 1)
  • (i+1) 是一个int。就让它str(i+1)。它会将其转换为字符串。

标签: python typeerror


【解决方案1】:

"abc" + (i+1) 正在向字符串添加一个整数。考虑使用这样的 f 字符串:

print(f"Starting Balance: for year {i+1} ${Starting_balance}")

它更具可读性并为您执行所需的转换。

【讨论】:

  • f-string 是什么意思?
  • @CWoolford f-strings 非常有用(在 3.6 或更高版本中可用),试试this tutorial
  • @CWoolford 请注意字符串是如何用f 预先固定的 - 这会导致它自动格式化,就像'string {}',format() 一样,但没有所有的绒毛。
【解决方案2】:

你只能连接两个字符串,你试图连接 int 和 str


InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))



TotalInterestEarned = 0
for i in range(Years):
      InterestEarned = round(InvestAmount*(Rate/100),2)
      EndingBal = round(InvestAmount+InterestEarned , 2)
      Starting_balance = (InvestAmount + InterestEarned)
      
      print("Starting Balance: for year " + str((i+1))+"$"+str(Starting_balance))  # change int to str as well str(i+1)  
      print("Ending balance: for year" +str((i+1))+"$"+str(EndingBal)) # same here 
      print("Total Interest Earned: for year" +str((i+1))+"$"+str(InterestEarned)) # same here

【讨论】:

    【解决方案3】:

    每个人都已经大致了解了解决方案,但我希望可以为那些不熟悉类型的人添加更多上下文。所以当你定义 i 时,它是一个 int。另一方面,您尝试放入的字符串是“Starting Balance:...”,这意味着它是一个字符串。使用整数5 + 5 = 10。添加整数是标准的。同样,python 足够聪明,可以理解"con" + "cat" = "concat",因为本质上你是在字符串的末尾。

    现在,当您执行 "con" + 5 = ERROR 时会发生什么,因为 python 不理解将整数添加到字符串意味着什么。这是否意味着您应该将 "con" 转换为整数表示并以这种方式添加 5,或者是否意味着将数字 5 添加到 "con5"? (请注意,某些语言允许这种添加,但有时会变得很奇怪。Python 是强类型的,因此我们不必考虑这种可能性。)

    换句话说,我们必须做出区分,否则我们的类型不匹配。在所有的解决方案中,我们正在将i+1 转换为某个字符串,通过制定str() 或f-strings。

    希望这可以澄清!

    【讨论】:

    • Python 是动态类型,不是强类型。 Python 通常不会在类型之间进行隐式转换——我认为,这正是您试图提出的观点。通常 = 执行 print(5) 无需执行 print(str(5)) 即可工作,因为 print 将在对象(继承或其他方式)上查找 __str____repr__ 方法并将其调用到 print 事物。很好,您注意到 Python 不会像 "con" + 5 那样进行隐式类型转换,这与其他一些语言不同 - 但这与强类型或动态类型无关。 "con" * 5 确实有效,产生 "conconconconcon"
    • 你说得对,但我不同意,它既是动态类型的,也是强类型的。它在运行时决定类型。强类型意味着你不能轻易混合类型。
    • 确实,Python 是强类型的(我说它不是强类型是不正确的)但是 不会影响类型的混合能力。这与Duck typing 有更多关系。只要x 具有支持y 类型的__add__y 具有支持x 类型的__radd__x + y 就可以工作。对于xy(动态)中的每一个,相同的表达式可以用于不同的类型,但它仅在两个对象满足上述条件时才有效(鸭子)。这就是为什么"con" * 5 有效而"con" + 5 无效的原因。我们在这两种情况下都混合了类型。
    【解决方案4】:

    你可以这样做:

    print(f"Starting Balance: for year {i+1} $ {Starting_balance}") 
    # and other code... 
    

    【讨论】:

      【解决方案5】:

      您只需要像这样将str 添加到 (i+1) 之前:

      print("Starting Balance: for year " + str((i + 1)) + " $" + str(Starting_balance))
      print("Ending balance: for year " + str((i + 1)) + " $" + str(EndingBal))
      print("Total Interest Earned: for year " + str((i + 1)) + " $" + str(InterestEarned))
      

      【讨论】:

        【解决方案6】:

        为了完整起见,另一种方法是使用 , 并让 print 函数完成它的工作。

        打印函数接受单个对象或多个对象,以,分隔,并将转换为字符串并打印在屏幕上。

        InvestAmount = int(input("Enter the intial investment amount: "))
        Years = int(input("Enter the number of years to invest: "))
        Rate = float(input("Enter the intrest rate (as %): "))
        
        
        TotalInterestEarned = 0
        for i in range(Years):
            InterestEarned = round(InvestAmount * ( Rate / 100),2)
            EndingBal = round(InvestAmount + InterestEarned , 2)
            Starting_balance = (InvestAmount + InterestEarned)
              
            print("Starting Balance: for year ", (i + 1), "$", Starting_balance)    
            print("Ending balance: for year", (i + 1), "$", EndingBal)
            print("Total Interest Earned: for year", (i + 1), "$", InterestEarned)
        

        不是最好的方法,其他答案要好得多。

        【讨论】: