开发者

How to check if an element of a list is a number?

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']
开发者_JAVA百科

Many thanks.


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] )


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"


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜