How can I tell when a string is in fact a number?
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
File "<stdin>", line 1
SyntaxError: invalid syntax
In addition to using re, you might try compile as a final check.
if re.match(r'(?i)\s*[\d.xje+-]+\s*$', inputStr) != None:
assert(isanum("1+2j") == 1)
assert(isanum("01.0") == 0)
More information about the Python-list