[Tutor] why different result from two similar ways

Prasad, Ramit ramit.prasad at jpmorgan.com
Tue Nov 6 17:31:05 CET 2012


Steven D'Aprano wrote:
> On 30/10/12 12:36, Frank Pontius wrote:
> > Hello,
> > I have code that works.  Then tried to move some of it into function
> > IncrementAndRebuildInput, then result changes, I no longer have same result
> > as when code in function was inline - why?
> 
> Have you tried running it in isolation to see what it does?
> 
> When I try it, it works for me (apart from printing a lot of unnecessary
> intermediate results):
> 
> py> result = IncrementAndRebuildInput("abc def 123 xyz 456")
> ['abc', 'def', '123', 'xyz', '456']
> 124
> ['abc', 'def', '124', 'xyz', '456']
> NOWHERE
> 457
> ['abc', 'def', '124', 'xyz', '457']
> NOWHERE
> ['abc', 'def', '124', 'xyz', '457']
> Point6
> 
> 
> 
> Now check the returned result:
> 
> py> result
> ['abc', 'def', '124', 'xyz', '457']
> 
> So it certainly does increment the numbers in the string. The only
> bit it doesn't do is rebuild the string, but that takes just one
> minor change: instead of "return newstring" (by the way, that's false
> advertising -- newstring is not a string, it is a list), use:
> 
>      return ' '.join(newstring)
> 
> 
> You also use this function:
> 
> > def IsNum(string):
> > #    print "IsNum string", string
> >      for char in string:             #checks string groupings to be all nums
> >          if not char.isdigit():
> > #            print "false"
> >              return False
> > #    print "true"
> >      return True
> 
> You don't need it! The isdigit method doesn't only work on a single character
> at a time, it works on an entire string:
> 
> py> "12345".isdigit()
> True
> py> "12345a".isdigit()
> False

I just want to point to the OP (Frank) that this only works for "digits" i.e. integers. It will fail for other types of numbers.

>>> '12.3'.isdigit()
False
>>> '12.3'.isalnum()
False

~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list