Python TypeError: cannot concatenate 'str' and 'int' objects when trying to print
Python TypeError: cannot concatenate 'str' and 'int' objects when trying to print
我 运行 在尝试制作一个计算器时遇到了这个问题,它需要几秒钟的时间并在 minutes:seconds 中给出时间的输出,并且它会产生这个错误
这是我的代码:
timeInSeconds = 1823
timeInMinutes = timeInSeconds / 60
timeInRest = timeInSeconds % 60
str(timeInMinutes)
str(timeInRest)
print("Your time in minutes and seconds is " + timeInMinutes + ":" + timeInRest)
改变
print("Your time in minutes and seconds is " + timeInMinutes + ":" + timeInRest)
至
print("Your time in minutes and seconds is " + str(timeInMinutes) + ":" + str(timeInRest))
您忘记重新分配新值:
timeInSeconds = 1823
timeInMinutes = timeInSeconds / 60
timeInRest = timeInSeconds % 60
timeInMinutes = str(timeInMinutes)
timeInRest = str(timeInRest)
print("Your time in minutes and seconds is " + timeInMinutes + ":" + timeInRest)
基本上是这样做的:
str(timeInMinutes)
并不意味着您的 TimeInMinutes 变量现在是一个字符串。您必须像这样重新分配它:
timeInMinutes = str(timeInMinutes)
我相信这就是你想要做的。
但是,保留 int 值以备后用可能会有用。如果是这种情况,您可以像这样创建新变量:
timeInMinutesStr = str(timeInMinutes)
timeInRestStr = str(timeInRest)
print("Your time in minutes and seconds is " + timeInMinutesStr + ":" + timeInRestStr)
或者,您可以直接在打印中转换值,以避免必须分配以后可能不会使用的新变量:
print("Your time in minutes and seconds is " + str(timeInMinutes) + ":" + str(timeInRest))
我 运行 在尝试制作一个计算器时遇到了这个问题,它需要几秒钟的时间并在 minutes:seconds 中给出时间的输出,并且它会产生这个错误
这是我的代码:
timeInSeconds = 1823
timeInMinutes = timeInSeconds / 60
timeInRest = timeInSeconds % 60
str(timeInMinutes)
str(timeInRest)
print("Your time in minutes and seconds is " + timeInMinutes + ":" + timeInRest)
改变
print("Your time in minutes and seconds is " + timeInMinutes + ":" + timeInRest)
至
print("Your time in minutes and seconds is " + str(timeInMinutes) + ":" + str(timeInRest))
您忘记重新分配新值:
timeInSeconds = 1823
timeInMinutes = timeInSeconds / 60
timeInRest = timeInSeconds % 60
timeInMinutes = str(timeInMinutes)
timeInRest = str(timeInRest)
print("Your time in minutes and seconds is " + timeInMinutes + ":" + timeInRest)
基本上是这样做的:
str(timeInMinutes)
并不意味着您的 TimeInMinutes 变量现在是一个字符串。您必须像这样重新分配它:
timeInMinutes = str(timeInMinutes)
我相信这就是你想要做的。
但是,保留 int 值以备后用可能会有用。如果是这种情况,您可以像这样创建新变量:
timeInMinutesStr = str(timeInMinutes)
timeInRestStr = str(timeInRest)
print("Your time in minutes and seconds is " + timeInMinutesStr + ":" + timeInRestStr)
或者,您可以直接在打印中转换值,以避免必须分配以后可能不会使用的新变量:
print("Your time in minutes and seconds is " + str(timeInMinutes) + ":" + str(timeInRest))