manipulate string
David C. Fox
davidcfox at post.harvard.edu
Tue Oct 28 13:22:11 EST 2003
> 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
More information about the Python-list
mailing list