0

For the following code, why is the answer not 'yoif!' with the exclamation mark?

>>> s = 'Python is fun!'

>>> s[1:12:3]

>'yoif'

Why is the exclamation mark excluded, since it also has an index number, as shown by the following code (continued from above)?

>>> s[13]

>'!'
khelwood
  • 55,782
  • 14
  • 81
  • 108
peractio
  • 593
  • 1
  • 5
  • 14

5 Answers5

0

Because that is how slicing works. It will pick the elements with indices starting at 1 and ending at max 12. Therefore, the only elements you see is of indices 1, 4, 7 and 10. 13 is the next step, but since it is above 12 so it will not show.

Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32
0

Your question provides the answer itself. You are slicing from 1st to 12th position(which is not inclusive). so you will get elements upto 11th position.

if you want to get ! change the value from 12 to 14. see below code.

s = 'Python is fun!'
print(s[1:14:3])

output:

'yoif!'
Sociopath
  • 13,068
  • 19
  • 47
  • 75
0

s = 'Python is fun!'

s[1:12] only returns string till 'ython is fu' hence a stride of 3 can't reach !

Where as

s[1:14] returns string till 'ython is fun!'.

s[1:14:3] 

output: 'yoif!'

As linked in the comment on the question by @Chris_Rands:

a[start:end] # items start through end-1
a[start:]    # items start through the rest of the array
a[:end]      # items from the beginning through end-1
a[:]         # a copy of the whole array

a[start:end:step] # start through not past end, by step
Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
0

You define 1 as the start of your sliced string, 12 at the end and 3 as the step. This is the general structure for slicing: [start:end:step]

With a start of 1 and a end of 12, your string looks like this: ython is fu

You have to set your end at the right position. So s[1:14] would print ython is fun!

When you add your step of 3 like this s[1:14:3] your code prints yoif! as you wanted to.

NK_
  • 361
  • 1
  • 4
  • 11
0

Slices, 0 indexed, are in the form [from : up to but not including : every]

To include the last element, exclude it from your slice and leave that part empty.

>>> "Python is fun!"[1::3] 'yoif!'

leaving 'from' empty makes it start at the beginning.

Leaving 'to' empty makes it go to the end.

"Python is fun!"[:] 'Python is fun!'

Dan
  • 1