TypeError:字符串对象不可调用

2024-10-03 06:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在第4行的TypeError上得到这个。我试过f-strings,甚至str(ageStr) / str(age)——我在第4行仍然遇到同样的错误

ageStr = "24" #I'm 24 years old.
age = int(ageStr)

print("I'm "+ ageStr +"years old.")
three = "3"

answerYears = age + int(three)

print("The total number of years:" + "answerYears")
answerMonths = answerYears*12 

print("In 3 years and 6 months, I'll be " + answerMonths + " months old"

Tags: theage错误oldintthreeprintstrings
2条回答

这是你的错误的解决方案

print("In 3 years and 6 months, I'll be " + str(answerMonths) + " months old")   

第二种解决方案是简单地删除字符串连接

print("In 3 years and 6 months, I'll be ", answerMonths, " months old")   

要打印时,需要将int变量显式类型转换为str:

ageStr = "24" #I'm 24 years old.
age = int(ageStr)

print("I'm "+ ageStr +"years old.")
three = "3"

answerYears = age + int(three)

print("The total number of years:" + str(answerYears))
answerMonths = answerYears*12 

print("In 3 years and 6 months, I'll be " + str(answerMonths) + " months old")

输出:

I'm 24years old.                                                                                                      
The total number of years:27                                                                                          
In 3 years and 6 months, I'll be 324 months old 

相关问题 更多 >