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:34

You can use the isdigit() method for strings. In this case, as you said the input is always a string:

    user_input = input("Enter something:")
    if user_input.isdigit():
        print("Is a number")
    else:
        print("Not a number")
查看更多
与风俱净
3楼-- · 2018-12-31 04:35

Here is the simplest solution:

a= input("Choose the option\n")

if(int(a)):
    print (a);
else:
    print("Try Again")
查看更多
不流泪的眼
4楼-- · 2018-12-31 04:36

Works fine for check if an input is a positive Integer AND in a specific range

def checkIntValue():
    '''Works fine for check if an **input** is
   a positive Integer AND in a specific range'''
    maxValue = 20
    while True:
        try:
            intTarget = int(input('Your number ?'))
        except ValueError:
            continue
        else:
            if intTarget < 1 or intTarget > maxValue:
                continue
            else:
                return (intTarget)
查看更多
孤独寂梦人
5楼-- · 2018-12-31 04:36

Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.

numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]

for item in numList:

    try:
        print (item / 2) #You can divide by any number really, except zero
    except:
        print "Not A Number: " + item

Result:

249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number: 
查看更多
妖精总统
6楼-- · 2018-12-31 04:36

I've been using a different approach I thought I'd share. Start with creating a valid range:

valid = [str(i) for i in range(-10,11)] #  ["-10","-9...."10"] 

Now ask for a number and if not in list continue asking:

p = input("Enter a number: ")

while p not in valid:
    p = input("Not valid. Try to enter a number again: ")

Lastly convert to int (which will work because list only contains integers as strings:

p = int(p)
查看更多
墨雨无痕
7楼-- · 2018-12-31 04:37

If you specifically need an int or float, you could try "is not int" or "is not float":

user_input = ''
while user_input is not int:
    try:
        user_input = int(input('Enter a number: '))
        break
    except ValueError:
        print('Please enter a valid number: ')

print('You entered {}'.format(a))

If you only need to work with ints, then the most elegant solution I've seen is the ".isdigit()" method:

a = ''
while a.isdigit() == False:
    a = input('Enter a number: ')

print('You entered {}'.format(a))
查看更多
登录 后发表回答