for loop question

Larry Bates larry.bates at websafe.com
Wed Oct 10 22:54:42 CEST 2007


Tim Chase wrote:
>> test = u"Hello World"
>>
>> for cur,next in test:
>>     print cur,next
>>
>> Ideally, this would output:
>>
>> 'H', 'e'
>> 'e', 'l'
>> 'l', 'l'
>> 'l', 'o'
>> etc...
>>
>> Of course, the for loop above isn't valid at all. I am just giving an
>> example of what I'm trying to accomplish. Anyone know how I can 
>> achieve the
>> goal in the example above? Thanks.
> 
> A "works-for-me":
> 
>  >>> pairs = (test[i:i+2] for i in xrange(len(test)-1))
>  >>> for a,b in pairs:
> ...     print a,b
> ...
> H e
> e l
> l l
> l o
> o
>   w
> w o
> o r
> r l
> l d
>  >>>
> 
> -tkc
> 
> 
> 
import itertools

test = u"Hello World"
ltest=["'%s'" % c for c in test]

for a, b in itertools.izip(ltest, ltest[1:]):
     print x, y

'H' 'e'
'e' 'l'
'l' 'l'
'l' 'o'
'o' ' '
' ' 'W'
'W' 'o'
'o' 'r'
'r' 'l'
'l' 'd'

-Larry



More information about the Python-list mailing list