Test for number?

Hardcoded Software 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 :
> 		Do_A
> else:
> 		Do_B
> ---
> 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
regexp:

import re
re_has_digit = re.compile(r'\d+')
try:
    digits = re_has_digit.findall(input)[0]
    number = int(digits)
    print "%d is a number." % number
except IndexError:
    print "'%s' has no number in it." % input

I didn't try it, but it should work.




More information about the Python-list mailing list