How do I check if a string is a number (float)?

后端 未结 30 4650
暗喜
暗喜 2020-11-21 05:16

What is the best possible way to check if a string can be represented as a number in Python?

The function I currently have right now is:

def is_numb         


        
30条回答
  •  没有蜡笔的小新
    2020-11-21 05:57

    The input may be as follows:

    a="50" b=50 c=50.1 d="50.1"


    1-General input:

    The input of this function can be everything!

    Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c) and binary (e.g. 0b10100111001) notation is not allowed.

    is_numeric function

    import ast
    import numbers              
    def is_numeric(obj):
        if isinstance(obj, numbers.Number):
            return True
        elif isinstance(obj, str):
            nodes = list(ast.walk(ast.parse(obj)))[1:]
            if not isinstance(nodes[0], ast.Expr):
                return False
            if not isinstance(nodes[-1], ast.Num):
                return False
            nodes = nodes[1:-1]
            for i in range(len(nodes)):
                #if used + or - in digit :
                if i % 2 == 0:
                    if not isinstance(nodes[i], ast.UnaryOp):
                        return False
                else:
                    if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                        return False
            return True
        else:
            return False
    

    test:

    >>> is_numeric("54")
    True
    >>> is_numeric("54.545")
    True
    >>> is_numeric("0x45")
    True
    

    is_float function

    Finds whether the given variable is float. float strings consist of optional sign, any number of digits, ...

    import ast
    
    def is_float(obj):
        if isinstance(obj, float):
            return True
        if isinstance(obj, int):
            return False
        elif isinstance(obj, str):
            nodes = list(ast.walk(ast.parse(obj)))[1:]
            if not isinstance(nodes[0], ast.Expr):
                return False
            if not isinstance(nodes[-1], ast.Num):
                return False
            if not isinstance(nodes[-1].n, float):
                return False
            nodes = nodes[1:-1]
            for i in range(len(nodes)):
                if i % 2 == 0:
                    if not isinstance(nodes[i], ast.UnaryOp):
                        return False
                else:
                    if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                        return False
            return True
        else:
            return False
    

    test:

    >>> is_float("5.4")
    True
    >>> is_float("5")
    False
    >>> is_float(5)
    False
    >>> is_float("5")
    False
    >>> is_float("+5.4")
    True
    

    what is ast?


    2- If you are confident that the variable content is String:

    use str.isdigit() method

    >>> a=454
    >>> a.isdigit()
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'int' object has no attribute 'isdigit'
    >>> a="454"
    >>> a.isdigit()
    True
    

    3-Numerical input:

    detect int value:

    >>> isinstance("54", int)
    False
    >>> isinstance(54, int)
    True
    >>> 
    

    detect float:

    >>> isinstance("45.1", float)
    False
    >>> isinstance(45.1, float)
    True
    

提交回复
热议问题