Python TypeError 必须是 str 而不是 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44916637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python TypeError must be str not int
提问by Eps12 Gaming
I am having trouble with the following piece of code:
我在使用以下代码时遇到问题:
if verb == "stoke":
if items["furnace"] >= 1:
print("going to stoke the furnace")
if items["coal"] >= 1:
print("successful!")
temperature += 250
print("the furnace is now " + (temperature) + "degrees!")
^this line is where the issue is occuring
else:
print("you can't")
else:
print("you have nothing to stoke")
The resulting error comes up as the following:
结果错误如下:
Traceback(most recent call last):
File "C:\Users\User\Documents\Python\smelting game 0.3.1 build
incomplete.py"
, line 227, in <module>
print("the furnace is now " + (temperature) + "degrees!")
TypeError: must be str, not int
I am unsure what the problem is as i have changed the name from temp to temperature and added the brackets around temperature but still the error occurs.
我不确定问题是什么,因为我已将名称从 temp 更改为温度并在温度周围添加了括号,但仍然发生错误。
回答by PYA
print("the furnace is now " + str(temperature) + "degrees!")
print("the furnace is now " + str(temperature) + "degrees!")
cast it to str
投给 str
回答by AChampion
Python comes with numerous ways of formatting strings:
Python 提供了多种格式化字符串的方法:
New style .format()
, which supports a rich formatting mini-language:
新样式.format()
,支持丰富格式的迷你语言:
>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!
Old style %
format specifier:
旧式%
格式说明符:
>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!
In Py 3.6 using the new f""
format strings:
在 Py 3.6 中使用新的f""
格式字符串:
>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!
Or using print()
s default sep
arator:
或者使用print()
s 默认sep
arator:
>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!
And least effectively, construct a new string by casting it to a str()
and concatenating:
最不有效的是,通过将其转换为 astr()
并连接来构造一个新字符串:
>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!
Or join()
ing it:
或者join()
它:
>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!
回答by badiya
you need to cast int to str before concatenating. for that use str(temperature)
. Or you can print the same output using ,
if you don't want to convert like this.
您需要在连接之前将 int 转换为 str 。对于那个用途str(temperature)
。或者,,
如果您不想像这样进行转换,则可以使用打印相同的输出。
print("the furnace is now",temperature , "degrees!")