-2

I am getting different strings, some are numbers, for example: "1", "afd76", "dddd", "521129" and "0.1423105". I need to check if they are valid numbers before I can continue. In the above examples all are numbers apart from "afd76" and "dddd".

isdigit and isnumeric wont do because they can only verify if the string is an int, for example:

"3".isdigit() is true but "3.0".isdigit() is false
"3".isnumeric() is true but "3.0".isnumeric() is false 

Is there any elegant way to do this check other than force casting and deciding what to do depending on the exception?

PloniStacker
  • 574
  • 4
  • 23

1 Answers1

3

You can try casting the string into float:

def is_number(num):
    try:
        float(num)
        return True
    except ValueError:
        return False

Examples:

>>> is_number('123')
True
>>> is_number('123a')
False
>>> is_number('123.12')
True
>>> is_number('3.0')
True
PApostol
  • 2,152
  • 2
  • 11
  • 21