[Tutor] Splitting a number into even- and odd- numbered digits

Carroll, Barry Barry.Carroll at psc.com
Thu Apr 20 02:17:09 CEST 2006


I am writing a function that accepts a string of decimal digits, calculates a checksum and returns it as a single character string.  
The first step in the calculation is to split the input into two strings: the even- and odd- numbered digits, respectively.  The least significant digit is defined as odd.  

The following code fragment does the job but seems sort of brutish and inelegant to me:

>>> s = '987654321'
>>> odd = ''
>>> for c in s[::-2]:
...     odd = c + odd
>>> s = s[:-1]
>>> even = ''
>>> for c in s[::-2]:
...     even = c + even
>>> odd
>>> even

Is there a better (i.e. more Pythonic) way to do this?  

Thanks in advance for all your help.

barry.carroll at psc.com
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed

More information about the Tutor mailing list