tags:

views:

120

answers:

3

How can I check if the first element of the list (below) is a number (using some sort of regular expression) in python:

temp = ['1', 'abc', 'XYZ', 'test', '1']

Many thanks.

+9  A: 
try:
  i = int(temp[0])
except ValueError:
  print "not an integer\n"

try:
  i = float(temp[0])
except ValueError:
  print "not a number\n"

If it must be done with a regex:

import re
re.match( '^[-+]?(([0-9]+([.][0-9]*)?)|(([0-9]*[.])?[0-9]+))$', temp[0] )
eruciform
If you're going to check for any other things inside the try block, make sure you `except ValueError`
Justin Poliey
How does this have the most votes? Empty except's, seriously? Edit: Oh, he fixed it now .. still, why can't you use regex as he asked, or one of the built-in functions? This is a code-heavy way
Bartek
I'm all for telling him the right thing to do, but you explicitly ignored the part of the question that said "use a regular expression" :)
Stephen
@justin: thanks, updated. @stephen: he said "some sort of regex" - I think he just wants a solution...
eruciform
You're probably right. Answers that don't use regex on questions that ask for regex always seem to get a lot of votes :)
Stephen
http://regex.info/blog/2006-09-15/247
Johnsyweb
updated: added regex solution as well
eruciform
That regex would accept things like "", ".", "-.", "0." which aren't traditionally accepted as numerics (well, "0." is in Python). So, +1 for the non-regex solution, will be faster, too.
Korbinian
@korbinian: true. updated. :-)
eruciform
+1  A: 

Using regular expressions (because you asked):

>>> import re
>>> if re.match('\d+', temp[0]): print "it's a number!"

Otherwise, just try to parse as an int and catch the exception:

>>> int(temp[0])

Of course, this all gets (slightly) more complicated if you want floats, negatives, scientific notation, etc. I'll leave that as an exercise to the asker :)

Stephen
Thanks a lot for your help guys.
DGT
+2  A: 

If you are just expecting a simple positive number, you can use the isDigit method of Strings.

if temp[0].isdigit(): print "It's a number"
linead