Search code examples
pythonstringslicepunctuationstride

Punctuation when slicing string in python with stride


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]

>'!'

Solution

  • 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