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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With