For a string, it can be used as variable_name[start:end:step]
If step is positive and start is greater than the end, then a null string is returned.
If step is negative and start is lesser than the end, then a null string is returned.
Let us see a simple slice example.
>>> i = “Hello World”
>>> i[2:10:1]
‘llo Worl’
In the above example, it returns the characters from the string whose position are equal to and greater than start and less than end.
In the above example i[10] = “d” is not returned.
If the start is not specified and step is positive, then the default value is 0
If the end is not specified and step is positive, then the default value is len(string).
If the start is not specified and step is negative then the default value is len(string).
If the end is not specified and step is negative, then the default value is NOT 0, coz in this case even 0th character is returned.
If the step is not specified, then the default value is 1
So i[::] prints the entire string. In fact, in most cases the step is not specified. So i[:] returns the entire string.
>>> i = “Hello World”
>>> i[::]
‘Hello World’
>>> i[:]
‘Hello World’
>>>
Slice notation can also take negative values.
If the start value is negative, then the last start characters are returned.
If the end value is negative, then the last end characters are not returned.
>>> i = “Hello World”
>>> i[-5:] #Start is -ve. So last 5 characters
‘World’
>>> i[:-5] #End is -ve. So everything except last 5 characters
‘Hello ‘
>>> i[-8:-3] #Start is -8. =>”lo World”. In this don’t include last 3 characters => “lo Wo”
‘lo Wo’
>>>
If the start is greater than the end, then the step must be -ve, which makes the string to be returned as reverse.
So consider this example.
>>> i = “Hello World”
>>> i[8:4:-1]
‘roW ‘
>>>
Finally, if step is something other than 1, then every stepth character is returned. For example
>>> i = “Hello World”
>>> i[::2]
‘HloWrd’
>>> i[::-2]
‘drWolH’
>>>
Any idea why i wrote this post.
Saw this small snippet for string reverse in python
>>> a = “Hello World”
>>> print a[::-1]
dlroW olleH
>>>
Sweet and cute na. ;-)
To know more about slice notation you refer to the python python doc.