2
s = "alphabet"
print(s[2:8:2])

this prints 'pae'

i understand that it starts counting from the left and starts from 0 so

0 = a
1 = l
2 = p
3 = h
4 = a
5 = b
6 = e
7 = t

so im not sure how the last :8 and :2] work

user3382238
  • 143
  • 1
  • 2
  • 11

1 Answers1

3

8 is the end index (exclusive), so only characters up to position 7 are included. 2 is the step size (also called stride), so only every second character is included.

Starting at 2, that means indices 2, 4, and 6 are included here, giving you p, a and e.

Because the end index is equal to the length, you get the same result if you omit that entry:

>>> s = "alphabet"
>>> s[2::2]
'pae'

or used None:

>>> s[2:None:2]
'pae'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343