pshx pshx - 5 months ago 7
Python Question

Need to get words at "even" indices from string

Here is a string as an example.

s = 'asdf df d f d ssa'.


I need to get words at even indices from a string.
A correct output would be
'df f ssa'

I think I would do this with a slice.

How might I go about this?

Answer

You meant words at even indices (if that sounds correct). split and then slice with a step of 2 starting at 1:

>>> ' '.join(s.split()[1::2])
'df f ssa'

Your even would mean odd here, since indexing starts from zero.

Comments