Help in string.digits functions

Simon Forman rogue_pedro at yahoo.com
Tue Jul 25 13:06:43 EDT 2006


John McMonagle wrote:
> On Mon, 2006-07-24 at 22:19 -0700, Anoop wrote:
> > Hi All
> >
> > I am getting two different outputs when i do an operation using
> > string.digits and test.isdigit(). Is there any difference between the
> > two. I have given the sample program and the output
> >
> > Thanks for ur inputs
> >
> > Anoop
> >
> > #1:
> > ~~
> > import string
> >
> > test='121206'
> >
> > if test not in string.digits:
> >     print "I am Not Digit"
> > else:
> >     print "I am Digit"
> >
> > #2:
> > ~~
> > import string
> >
> > test='121206'
> >
> > if not test.isdigit():
> >     print "I am Not Digit"
> > else:
> >     print "I am Digit"
> >
> > Output
> > ~~~~~
> > #1:I am Not Digit
> > #2:I am Digit
> >
> > Thnks and Rgds
> >
> > Anoop
> >
>
>
> string.digits is the string constant '0123456789'
>
> So your test, "if test not in string.digits:" will evaluate True because
> '121206' is not in '0123456789'.
>
> Whereas test.isdigit() returns true if all the characters in test are
> digits.
>
> So yes, there is a big difference between the two.
>
> Regards,
>
> John
>
>
>


Your first test could be rewritten to do what I think you're thinking
it should do like so:

import string

test='121206'

for ch in test:
    if ch not in string.digits:
        print "I am not all Digits"
        break
else:
    print "I am all Digits"

But isdigit() would be the better way.


Peace,
~Simon




More information about the Python-list mailing list