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.
wow ! sweet and cute ๐ ๐
sweet and cute ! what kind of expression is this !!.
i though sexy wud have been apt but hey ! not that i dont know why sweet and cute are coming out ๐
you people are hopeless !!!
I’ve written a nice tutorial. Looks like no one has even saw that ๐ All you saw is “sweet and cute” ๐
And yeah the code is “sweet and cute”. Hmmmm you may call it sexy if you want, but i prefer sweet and cute ๐
You know, it did ring out rather odd – I remember getting such an impression when I read the post before these comments and I thought I was imagining it.
the command i liked most was
a = “Hello World”
>>> print a[::-1]
dlroW olleH
Python rocks.
thanks for the nice short, cute info :).Please do write more blog posts on python .
@lavi: yeah it rocks ๐ will try to post more ๐