[Tutor] why different result from two similar ways

Steven D'Aprano steve at pearwood.info
Tue Nov 6 03:18:29 CET 2012


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




-- 
Steven


More information about the Tutor mailing list