isNumber? check
Skip Montanaro
skip at pobox.com
Mon Sep 29 17:05:40 EDT 2003
>> if expr.strip("0123456789.e") == "": print "May be a number!"
>> if expr.strip("0123456789") == "": print "Surely a number!"
Rob> I don't like that solution for this particular project because, as
Rob> you say yourself, if it says yes to the second question, it only
Rob> *may* be a number. I want to know for sure.
Expanding on my previous post, here are a couple *simple-minded* re's for
matching ints and floats (really, fixed-point numbers)
>>> import re
>>> ipat = re.compile("([0-9]+)$")
>>> fpat = re.compile("([0-9]+\.[0-9]*$)")
>>> token = "123"
>>> fpat.match(token)
>>> print fpat.match(token)
None
>>> print ipat.match(token)
<_sre.SRE_Match object at 0x40d6a0>
>>> print ipat.match(token).group(1)
123
>>> token = "123.456"
>>> print ipat.match(token)
None
>>> print fpat.match(token)
<_sre.SRE_Match object at 0x487960>
>>> print fpat.match(token).group(1)
123.456
Extension of this idea to useful definitions for your interpreter is left as
an exercise for the reader.
Skip
More information about the Python-list
mailing list