Test for number?
hardcoded.software at gmail.com
Mon Sep 4 21:15:26 CEST 2006
Dr. Pastor wrote:
> In the following code I would like to ascertain
> that x has/is a number. What the simplest TEST should be?
> (Could not find good example yet.)
> x=raw_input('\nType a number from 1 to 20')
> if TEST :
> Thanks for any guidance.
> ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
> ----= East and West-Coast Server Farms - Total Privacy via Encryption =----
To test if it *is* a number, the solution is pretty simple (s.isdigit()
or an int(s) in a try..except ValueError), but if you want to test if
it is or *has* a number, I think that the simplest solution would be a
re_has_digit = re.compile(r'\d+')
digits = re_has_digit.findall(input)
number = int(digits)
print "%d is a number." % number
print "'%s' has no number in it." % input
I didn't try it, but it should work.
More information about the Python-list