令人困惑的python - 无法将字符串转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19736589/
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
Confusing python - Cannot convert string to float
提问by Turbo
I got a value error and even if I try playing around with the code, it doesn't work!
我收到了一个值错误,即使我尝试使用代码,它也不起作用!
How can I get it right? - I am using Python 3.3.2!
我怎样才能做对?- 我正在使用 Python 3.3.2!
Here is the code:
这是代码:
As you can see, the program asks for how many miles you can walk and gives you a response depending on what you type in.
如您所见,该程序会询问您可以步行多少英里,并根据您输入的内容给出响应。
This is the code in text format:
这是文本格式的代码:
print("Welcome to Healthometer, powered by Python...")
miles = input("How many miles can you walk?: ")
if float(miles) <= 0:
print("Who do you think you are?!! Go and walk 1000 miles now!")
elif float(miles) >= 10:
print("You are very healthy! Keep it up!")
elif float(miles) > 0 and miles < 10:
print("Good. Try doing 10 miles")
else:
print("Please type in a number!")
miles = float(input("How many miles can you walk?: "))
if miles <= 0:
print("Who do you think you are?!! Go and walk 1000 miles now!")
elif miles >= 10:
print("You are very healthy! Keep it up!")
elif miles > 0 and miles < 10:
print("Good. Try doing 10 miles")
采纳答案by Matt Reynolds
The problem is exactly what the Traceback log says: Could not convert string to float
问题正是回溯日志所说的: Could not convert string to float
- If you have a string with only numbers, python's smart enough to do what you're trying and converts the string to a float.
- If you have a string with non-numerical characters, the conversion will fail and give you the error that you were having.
- 如果您有一个只有数字的字符串,python 足够聪明,可以执行您正在尝试的操作并将字符串转换为浮点数。
- 如果您有一个包含非数字字符的字符串,则转换将失败并给出您遇到的错误。
The way most people would approach this problem is with a try/except
(see here), or using the isdigit()
function (see here).
大多数人解决此问题的方式是使用 a try/except
(请参阅此处)或使用isdigit()
函数(请参阅此处)。
Try/Except
尝试/除外
try:
miles = float(input("How many miles can you walk?: "))
except:
print("Please type in a number!")
Isdigit()
Isdigit()
miles = input("How many miles can you walk?: ")
if not miles.isdigit():
print("Please type a number!")
Note that the latter will still return false if there are decimal points in the string
注意,如果字符串中有小数点,后者仍然会返回false
EDIT
编辑
Okay, I won't be able to get back to you for a while, so I'll post the answer just in case.
好的,我有一段时间不能回复你,所以我会发布答案以防万一。
while True:
try:
miles = float(input("How many miles can you walk?: "))
break
except:
print("Please type in a number!")
#All of the ifs and stuff
The code's really simple:
代码非常简单:
- It will keep trying to convert the input to a float, looping back to the beginning if it fails.
- When eventually it succeeds, it'll break from the loop and go to the code you put lower down.
- 它将继续尝试将输入转换为浮点数,如果失败则循环回到开头。
- 当它最终成功时,它会跳出循环并转到您放低的代码。
回答by Simeon Visser
You need to take into account that the user might not fill in a proper value:
您需要考虑到用户可能没有填写正确的值:
try:
miles = float(input("How many miles can you walk? "))
except ValueError:
print("That is not a valid number of miles")
A try/except
handles the ValueError
that might occur when float
tries to convert the input to a float.
Atry/except
处理尝试将输入转换为浮点数ValueError
时可能发生的情况float
。
回答by roippi
The traceback means what it says on the tin.
回溯意味着它在锡上所说的。
>>> float('22')
22.0
>>> float('a lot')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a lot'
float
can convert strings that look like valid decimals into float
s. It can't convert arbitrary alphanumeric strings, notably including 'How am I supposed to know?'
.
float
可以将看起来像有效小数的字符串转换为float
s。它不能转换任意的字母数字字符串,特别是包括'How am I supposed to know?'
.
If you want to handle arbitrary user input, you have to catch this exception, with a try/except
block.
如果要处理任意用户输入,则必须使用try/except
块捕获此异常。
回答by Felipe R Valera
The point here it can not convert alphanumeric strings, in some cases if you are scraping data or something like $400, $ symbol is alphanumeric then it consider an string, if you try convert to float it display an error, i give you this example to show it only convert numbers to float, in this case i solved the problem like this data ='$400', price = data[1:], then if , if (float(price) < 300): and it works.
这里的重点是它不能转换字母数字字符串,在某些情况下,如果您正在抓取数据或类似 $400 的东西,$ 符号是字母数字然后它会考虑一个字符串,如果您尝试转换为浮动它会显示错误,我给你这个例子显示它只将数字转换为浮点数,在这种情况下,我解决了这样的问题 data ='$400', price = data[1:], then if , if (float(price) < 300): 并且它有效。