Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a reliable isnumeric() function for python 3?

I am attempting to do what should be very simple and check to see if a value in an Entry field is a valid and real number. The str.isnumeric() method does not account for "-" negative numbers, or "." decimal numbers.

I tried writing a function for this:

def IsNumeric(self, event):
    w = event.widget
    if (not w.get().isnumeric()):
        if ("-" not in w.get()):
            if ("." not in w.get()):
                w.delete(0, END)
                w.insert(0, '')

This works just fine until you go back and type letters in there. Then it fails.

I researched the possibility of using the .split() method, but I could not figure out a reliable regex to deal for it.

This is a perfectly normal thing that needs to be done. Any ideas?

like image 578
texasman1979 Avatar asked Jun 15 '15 21:06

texasman1979


1 Answers

try:
    float(w.get())
except ValueError:
    # wasn't numeric
like image 121
Ethan Furman Avatar answered Oct 27 '22 15:10

Ethan Furman