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

Darrell Gallion darrell at
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

>>> 01.1
  File "<stdin>", line 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:
            return 1
            return 0
    return 0

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


More information about the Python-list mailing list