Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 221
DGT Avatar asked Dec 03 '22 12:12

DGT


2 Answers

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] )
like image 167
eruciform Avatar answered Dec 24 '22 04:12

eruciform


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"
like image 33
linead Avatar answered Dec 24 '22 06:12

linead