【发布时间】:2016-03-29 07:01:21
【问题描述】:
我知道之前有人问过并回答过类似的问题:How do I check if a string is a number (float) in Python?
但是,它没有提供我正在寻找的答案。我想要做的是:
def main():
print "enter a number"
choice = raw_input("> ")
# At this point, I want to evaluate whether choice is a number.
# I don't care if it's an int or float, I will accept either.
# If it's a number (int or float), print "You have entered a number."
# Else, print "That's not a number."
main()
大多数问题的答案都建议使用 try..except,但这仅允许我专门评估 int 或 floats,即
def is_number(s):
try:
float(choice)
return True
except ValueError:
return False
如果我使用此代码,int 值将在异常中结束。
我见过的其他方法包括 str.isdigit。但是,这对于 int 返回 True,对于 float 则返回 false。
【问题讨论】:
-
float('123')返回123.0并且不给你ValueError。所以你的功能工作正常。 -
“如果我使用此代码,int 值将出现在异常中” - 不。请在询问之前实际尝试这些事情。
-
感谢各位的澄清。在问这个之前我确实尝试过这种方法,但我无法让它发挥作用。一定是在某个地方犯了错误。无论哪种方式,它现在就像你们提到的那样工作。谢谢!!
-
这能回答你的问题吗:Checking whether a variable is an integer or notThomas
标签: python string floating-point int