How to check if string input is a number? [duplica

2018-12-31 03:46发布

This question already has an answer here:

How do I check if a user's string input is a number (e.g. -1, 0, 1, etc.)?

user_input = input("Enter something:")

if type(user_input) == int:
    print("Is a number")
else:
    print("Not a number")

The above won't work since input always returns a string.

24条回答
明月照影归
2楼-- · 2018-12-31 04:38

This works with any number, including a fraction:

import fractions

def isnumber(s):
   try:
     float(s)
     return True
   except ValueError:
     try: 
       Fraction(s)
       return True
     except ValueError: 
       return False
查看更多
只靠听说
3楼-- · 2018-12-31 04:40

This solution will accept only integers and nothing but integers.

def is_number(s):
    while s.isdigit() == False:
        s = raw_input("Enter only numbers: ")
    return int(s)


# Your program starts here    
user_input = is_number(raw_input("Enter a number: "))
查看更多
查无此人
4楼-- · 2018-12-31 04:42

I think that what you'd be looking for here is the method isnumeric() (Documentation for python3.x):

>>>a = '123'
>>>a.isnumeric()
true

Hope this helps

查看更多
与君花间醉酒
5楼-- · 2018-12-31 04:42

the most elegant solutions would be the already proposed,

a=123
bool_a = a.isnumeric()

Unfortunatelly it doesn't work both for negative integers and for general float values of a. If your point is to check if 'a' is a generic number beyond integers i'd suggest the following one, which works for every kind of float and integer :). Here is the test:

def isanumber(a):

    try:
        float(repr(a))
        bool_a = True
    except:
        bool_a = False

    return bool_a


a = 1 # integer
isanumber(a)
>>> True

a = -2.5982347892 # general float
isanumber(a)
>>> True

a = '1' # actually a string
isanumber(a)
>>> False

I hope you find it useful :)

查看更多
其实,你不懂
6楼-- · 2018-12-31 04:43

I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):

This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)

a=(raw_input("Amount:"))

try:
    int(a)
except ValueError:
    try:
        float(a)
    except ValueError:
        print "This is not a number"
        a=0


if a==0:
    a=0
else:
    print a
    #Do stuff
查看更多
高级女魔头
7楼-- · 2018-12-31 04:43

Based on inspiration from answer. I defined a function as below. Looks like its working fine. Please let me know if you find any issue

def isanumber(inp):
    try:
        val = int(inp)
        return True
    except ValueError:
        try:
            val = float(inp)
            return True
        except ValueError:
            return False
查看更多
登录 后发表回答