Python 类型错误:只能将 str(不是“float”)连接到 str
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52796600/
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
TypeError: can only concatenate str (not "float") to str
提问by J_Zoio
I'm trying to make a program that compares the density of a certain mass and volume to a list of densities of compounds, and return the type of compound I am analyzing.
我正在尝试制作一个程序,将特定质量和体积的密度与化合物密度列表进行比较,并返回我正在分析的化合物类型。
This is the part of the code that is returning an error:
这是返回错误的代码部分:
peso = float(input("Qual o peso do plastico da sua protese?"))
volume = float(input("Qual o volume do material?"))
str(peso)
str(volume)
def resultados():
print('O peso do plastico é de ' + peso, end="", flush=True)
resultados()
print(' g e tem um volume de ' + volume + "dm^3")
The error message:
错误信息:
TypeError Traceback (most recent call last)
<ipython-input-9-d36344c01741> in <module>()
8 print('O peso do plastico é de ' + peso, end="", flush=True)
9
---> 10 resultados()
11 print(' g e tem um volume de ' + volume + "dm^3")
12 #############
<ipython-input-9-d36344c01741> in resultados()
6
7 def resultados():
----> 8 print('O peso do plastico é de ' + peso, end="", flush=True)
9
10 resultados()
TypeError: can only concatenate str (not "float") to str
回答by vash_the_stampede
You have some options about how to go about this
你有一些关于如何去做的选择
Using peso = str(peso)
and same for volume = str(volume)
使用peso = str(peso)
和相同的volume = str(volume)
peso = float(input("Qual o peso do plastico da sua protese?"))
volume = float(input("Qual o volume do material?"))
peso = str(peso)
volume = str(volume)
def resultados():
print('O peso do plastico é de ' + peso, end="", flush=True)
resultados()
print(' g e tem um volume de ' + volume + "dm^3")
Or you could just convert them to str
when you are performing your print
this way you can preserve the values as floats
if you want to do more calculations and not have to convert them back and forth over and over
或者您可以将它们转换为str
当您以print
这种方式执行时,您可以保留这些值,floats
就像您想要进行更多计算一样,而不必一遍又一遍地来回转换它们
peso = float(input("Qual o peso do plastico da sua protese?"))
volume = float(input("Qual o volume do material?"))
def resultados():
print('O peso do plastico é de ' + str(peso), end="", flush=True)
resultados()
print(' g e tem um volume de ' + str(volume) + "dm^3")
回答by Eduardo Soares
You have to assign the cast to the variable. Onlystr(peso)
doesn't modify it. Because str()
returns a str type
. So, you need to do that:
您必须将强制转换分配给变量。只是str(peso)
不修改它。因为str()
返回一个str type
. 所以,你需要这样做:
peso = str(peso)
回答by Dipan Mandal
Use formatted string
使用格式化字符串
str_val = "Hello"
int_val = 1234
msg = f'String and integer concatenation : {str_val} {int_val}'
Output
输出
String and integer concatenation : Hello 1234