如何检查Python 2.7中的字符串是否为(int或float)

时间:2015-12-22 22:35:23

标签: python string floating-point int

我知道在此之前已经提出并回答过类似的问题: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或float进行求值,即

def is_number(s):
    try:
        float(choice)
        return True
    except ValueError:
        return False

如果我使用此代码,则int值将以异常结束。

我见过的其他方法包括str.isdigit。但是,这对于int返回True,对于float返回false。

5 个答案:

答案 0 :(得分:3)

在你的情况下,只需检查输入是否可以转换为try / except块中的float。对于任何本可以转换为整数的字符串,转换都会成功。

答案 1 :(得分:2)

您使用的函数应该成功地将字符串形式的int和float值转换为float。出于某种原因,你想特别想找到天气,这是一个int或float考虑这个变化。

def is_int_or_float(s):
    ''' return 1 for int, 2 for float, -1 for not a number'''
    try:
        float(s)

        return 1 if s.count('.')==0 else 2
    except ValueError:
        return -1
print is_int_or_float('12')
print is_int_or_float('12.3')
print is_int_or_float('ads')

这是结果

python test.py
1
2
-1

答案 2 :(得分:1)

您可以编写自己的函数,

def is_int_or_float(a):
    if type(a) is int or type(a) is float:
        return True
    else:
       return False

你可以编写更紧凑的程序。请自己来做。

谢谢!

答案 3 :(得分:0)

您可以使用isstance()方法和literal_eval

例如

from ast import literal_eval

   isinstance(literal_eval('3'),int)

返回

True

或者你可以使用json。

import json

isinstance(json.loads('3'),int)

返回

True

答案 4 :(得分:0)

我知道这是旧的,但我做了一个简单的检查:

    var = 3

    try: #if it can be converted to a float, it's true
        float(var) 
    except: # it it can't be converted to a float, it's false
        do stuff with the var