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

natural: [0, 1, 2 ... ∞]

Python 2

it_is = unicode(user_input).isnumeric()

Python 3

it_is = str(user_input).isnumeric()

integer: [-∞, .., -2, -1, 0, 1, 2, ∞]

try:
    int(user_input)
    it_is = True
 except ValueError:
    it_is = False

float: [-∞, .., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1, ..., ∞]

try:
    float(user_input)
    it_is = True
 except ValueError:
    it_is = False
查看更多
还给你的自由
3楼-- · 2018-12-31 04:26

If you wanted to evaluate floats, and you wanted to accept NaNs as input but not other strings like 'abc', you could do the following:

def isnumber(x):
    import numpy
    try:
        return type(numpy.float(x)) == float
    except ValueError:
        return False
查看更多
孤独寂梦人
4楼-- · 2018-12-31 04:28

EDITED: You could also use this below code to find out if its a number or also a negative

import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
    print "given string is number"

you could also change your format to your specific requirement. I am seeing this post a little too late.but hope this helps other persons who are looking for answers :) . let me know if anythings wrong in the given code.

查看更多
倾城一夜雪
5楼-- · 2018-12-31 04:28

Here is a simple function that checks input for INT and RANGE. Here, returns 'True' if input is integer between 1-100, 'False' otherwise

def validate(userInput):

    try:
        val = int(userInput)
        if val > 0 and val < 101:
            valid = True
        else:
            valid = False

    except Exception:
        valid = False

    return valid
查看更多
浮光初槿花落
6楼-- · 2018-12-31 04:29

Apparently this will not work for negative values, but it will for positive. Sorry about that, just learned about this a few hours ago myself as I have just recently gotten into Python.

Use isdigit()

if userinput.isdigit():
    #do stuff
查看更多
伤终究还是伤i
7楼-- · 2018-12-31 04:29

I would recommend this, @karthik27, for negative numbers

import re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')

Then do whatever you want with that regular expression, match(), findall() etc

查看更多
登录 后发表回答