Determine Whether a String Value is Numeric in Python
It is pretty easy to determine whether a String object is an integer in Python, but the functionality is a bit obscured by a misnomer. This can be done using a function called isdigit.
x = "123"
x.isdigit() // True
However, this has some limitations. It only works with deciphering positive integers. For example:
x = "1.23"
x.isdigit() // False
y = "-1"
y.isdigit() // False
To get around this limitation, you have to use some more advanced techniques. However, how advanced you get depends on the requirements of what you’re using it for. For example, the following function, while imperfect, could work in a lot of cases.
def isnumeric(value):
return str(value).replace(".", "").replace("-", "").isdigit()
isnumeric("123") // True
isnumeric("1.23") // True
isnumeric("-1") // True
isnumeric("-1.23") // True
isnumeric("abc") // False
isnumeric(".-2") // True ... an example of how this is not perfect
While this technique may not work in all cases, it should be “good enough” for a large proportion. If you need to get more advanced, you’ll probably need to use regular expressions.
Feedback? Suggestions?
def isnumeric(value):
try:
int(value)
return True
except:
return False
def isnumeric(value):
try:
int(value)
return True
except:
return False
it works perfect, but there is a big problem…it is extremely slow…
the first option is really fast
whatever works for you, I prefer the one that is correct all the time and not just in most cases.
And what do you mean by “extremely slow”? is it taking a min or an hour? I doubt that, the time difference is almost unnoticeable unless you are doing thousands of checks.
Anvesh, in the post I mention it may not work for all cases. But I don’t know of any cases where it wouldn’t work. Do you? If so, I could tweak the code to handle those possibly.
I would consider this case as not working. This is a false positive. The test passes even though it shouldn’t.
isnumeric(“.-2″) // True
similarly
“2.22.2-”
That’s true. Good point. However, I have never come across such values in practice. I think the point of all of this is that you have to evaluate your needs for a given task, and sometimes a simple but unconventional approach can do the trick. Sometimes we may want to sacrifice accuracy for speed. And vice versa.
Wow guys..
def is_numeric(val):
try:
float(val)
except ValueError, e:
return False
return True
“.-02″ FALSE
“-.02″ TRUE
“.02.” FALSE
“02.-” FALSE
“0.00″ True
“-1.2″ TRUE