manipulate string
David C. Fox
davidcfox at post.harvard.edu
Tue Oct 28 13:25:49 EST 2003
David C. Fox wrote:
>> import string
>> a='0123456789'
>> l=list(a[::2])
>> b=string.join(l,' - ')
>> print b
>
>
> Chris wrote:
>
>> It is me again.
>> Unfortunately it doesn't work. Python doesn't accept [::2]
>> TypeError: sequence index must be integer
>> I use Python Release 2.2.3.
>> Any ideas?
>>
>> -Tom
>>
>
> Yeah, the x[::i] notation for strings and lists only works in 2.3.
>
> A couple of alternatives to l = list(a[::2]) which work in 2.2 are:
>
> l = []
> for i in range( (len(a) + 1) // 2):
> l.append(a[2*i])
>
> or more compactly
>
> l=[a[2*i] for i in range((len(a)+1)//2)]
>
> or
>
> l = [a[i] for i in range(len(a)) if 2*(i//2) == i]
>
> David
>
or
l = [a[i] for i in range(0, len(a), 2)]
David
More information about the Python-list
mailing list