How to check if a list item is a number?

How to check if the first element of a list (see below) is a number (using some kind of regular expression) in python:

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

Many thanks.

+3
source share
3 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 you need to do this with a regex:

import re
re.match( '^[-+]?(([0-9]+([.][0-9]*)?)|(([0-9]*[.])?[0-9]+))$', temp[0] )
+11
source

If you just expect a simple positive number, you can use the IsDigit method for strings.

if temp[0].isdigit(): print "It a number"
+4
source

Using regular expressions (because you asked):

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

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

>>> int(temp[0])

Of course, all this gets a little more complicated if you want floats, negatives, scientific notation, etc. I will leave this as an exercise for the seeker :)

+1
source

Source: https://habr.com/ru/post/1754158/


All Articles