pshx pshx - 1 year ago 65
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download