Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string is (int or float) in Python 2.7

I know similar questions have been asked and answered before like here: How do I check if a string is a number (float) in Python?

However, it does not provide the answer I'm looking for. What I'm trying to do is this:

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()

Answers to most of the questions suggest using try..except, but this only allows me to evaluate int or floats exclusively, i.e

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

If I use this code, int values will end up in the exception.

Other methods I've seen include str.isdigit. However, this returns True for int and false for float.

like image 994
wcj Avatar asked Mar 14 '23 19:03

wcj


2 Answers

In your case it is enough to simply check whether the input can be converted to a float in a try/except block. The conversion will be successful for any string that could have been converted to an integer as well.

like image 178
timgeb Avatar answered Mar 17 '23 04:03

timgeb


the function you used should be converting int and float values in the form of a string to a float successfully. for some reason you want to specifically want to find weather it is an int or float consider this change.

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')

here is the result

python test.py
1
2
-1
like image 30
rajesh.kanakabandi Avatar answered Mar 17 '23 04:03

rajesh.kanakabandi