[Tutor] Iterating over a string: index and value

Victor Bouffier victor at grupocdm.com
Sat Feb 11 06:08:44 CET 2006


On Fri, 2006-02-10 at 12:42 -0800, Carroll, Barry wrote:
> I seem to recall reading somewhere that it is possible to concurrently
> generate the index and value of a string’s characters in a single for
> statement.  Is this true or did imagine it?
> 
>  
> 
> Here is the scenario:
> 
>  
> 
> Given an ASCII string of arbitrary length and content, generate a
> sequence of tuples whose elements are: 
> 
>     the index of each character in the string, and 
> 
>     data based on the ordinal value of the character in the ASCII
> collating sequence.  
> 

Hi Barry,

Have a look at enumerate:

>>> list(enumerate('abcdefghijk'))
[(0, 'a'),
 (1, 'b'),
 (2, 'c'),
 (3, 'd'),
 (4, 'e'),
 (5, 'f'),
 (6, 'g'),
 (7, 'h'),
 (8, 'i'),
 (9, 'j'),
 (10, 'k')]

You need to work on each tuple in the iterable, but the function takes
you halfway.
Hope it helps.

Victor





More information about the Tutor mailing list