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

后端 未结 30 3968
暗喜
暗喜 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:35

    This answer provides step by step guide having function with examples to find the string is:

    • Positive integer
    • Positive/negative - integer/float
    • How to discard "NaN" (not a number) strings while checking for number?

    Check if string is positive integer

    You may use str.isdigit() to check whether given string is positive integer.

    Sample Results:

    # For digit
    >>> '1'.isdigit()
    True
    >>> '1'.isalpha()
    False
    

    Check for string as positive/negative - integer/float

    str.isdigit() returns False if the string is a negative number or a float number. For example:

    # returns `False` for float
    >>> '123.3'.isdigit()
    False
    # returns `False` for negative number
    >>> '-123'.isdigit()
    False
    

    If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

    def is_number(n):
        try:
            float(n)   # Type-casting the string to `float`.
                       # If string is not a valid `float`, 
                       # it'll raise `ValueError` exception
        except ValueError:
            return False
        return True
    

    Sample Run:

    >>> is_number('123')    # positive integer number
    True
    
    >>> is_number('123.4')  # positive float number
    True
    
    >>> is_number('-123')   # negative integer number
    True
    
    >>> is_number('-123.4') # negative `float` number
    True
    
    >>> is_number('abc')    # `False` for "some random" string
    False
    

    Discard "NaN" (not a number) strings while checking for number

    The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

    >>> is_number('NaN')
    True
    

    In order to check whether the number is "NaN", you may use math.isnan() as:

    >>> import math
    >>> nan_num = float('nan')
    
    >>> math.isnan(nan_num)
    True
    

    Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

    # `nan_num` variable is taken from above example
    >>> nan_num == nan_num
    False
    

    Hence, above function is_number can be updated to return False for "NaN" as:

    def is_number(n):
        is_number = True
        try:
            num = float(n)
            # check for "nan" floats
            is_number = num == num   # or use `math.isnan(num)`
        except ValueError:
            is_number = False
        return is_number
    

    Sample Run:

    >>> is_number('Nan')   # not a number "Nan" string
    False
    
    >>> is_number('nan')   # not a number string "nan" with all lower cased
    False
    
    >>> is_number('123')   # positive integer
    True
    
    >>> is_number('-123')  # negative integer
    True
    
    >>> is_number('-1.12') # negative `float`
    True
    
    >>> is_number('abc')   # "some random" string
    False
    

    PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

提交回复
热议问题