How can I tell when a string is in fact a number?

Darrell Gallion darrell at dorb.com
Sun Nov 5 23:25:14 CET 2000


On 5 Nov 2000, Gaute B Strokkenes wrote:
>
>
> def isanum(str):
>
> As the comment says, I'm sure there must be a more straightforward way
> to do this.  However, I can't find out how, though I'm sure that it is
> really my relative unfamiliarity with Python that is to blame.

Depending on your needs this can be tricky if you include floats or hex for
instance.

>>> 01.1
  File "<stdin>", line 1
    01.1
       ^
SyntaxError: invalid syntax

In addition to using re, you might try compile as a final check.

import re
def isanum(inputStr):
    if re.match(r'(?i)\s*[\d.xje+-]+\s*$', inputStr) != None:
        try:
            compile(inputStr,"",'eval')
            return 1
        except:
            return 0
    return 0

assert(isanum("-01")==1)
assert(isanum("+1.00E3") ==1)
assert(isanum("1+2j") == 1)
assert(isanum("01.0") == 0)


--Darrell










More information about the Python-list mailing list