TypeError:必须为str,而不是int Python3问题

时间:2018-11-05 17:00:16

标签: python python-3.x debugging

第6行怎么了?

 name = (input('Hi, please enter your name '))
dob = int(input('Hi please enter your DOB '))
today = int(input("Hi please enter today's date "))
future = int(today + 5)
diff = str(future - dob)
print ('Hi ' + name + 'in the year of ' + future + 'you will turn ' + diff)

我不断收到错误消息:

TypeError: must be str, not int

你们一般如何调试?我是编程新手。有没有办法确切知道它要在哪里字符串?

2 个答案:

答案 0 :(得分:1)

Python无法自动将整数变量转换为字符串。

您需要像这样将future变量显式转换为str类型:

print ('Hi ' + name + 'in the year of ' + str(future) + 'you will turn ' + diff)

答案 1 :(得分:0)

future整数,因此不能与字符串连接。您可以这样做:

print ('Hi ' + name + 'in the year of ', future, 'you will turn ' + diff)

或将int强制转换为str

print ('Hi ' + name + 'in the year of ' + str(future) + 'you will turn ' + diff)

示例:

name = (input('Hi, please enter your name '))
dob = int(input('Hi please enter your DOB '))
today = int(input("Hi please enter today's date "))
future = int(today + 5)
diff = str(future - dob)
print ('Hi ' + name + 'in the year of ', future, 'you will turn ' + diff)

输出:

C:\Users\Documents>py test.py
Hi, please enter your name job
Hi please enter your DOB 1876
Hi please enter today's date 2018
Hi jobin the year of  2023 you will turn 147

示例:

name = (input('Hi, please enter your name '))
dob = int(input('Hi please enter your DOB '))
today = int(input("Hi please enter today's date "))
future = int(today + 5)
diff = str(future - dob)
print ('Hi ' + name + 'in the year of ' + str(future) + 'you will turn ' + diff)

输出:

Hi, please enter your name job
Hi please enter your DOB 1876
Hi please enter today's date 2018
Hi jobin the year of 2023you will turn 147