What happens when we give string[::-1] in python such that the string gets reversed we know that by default the places are acquired by the 0 index and the last index+1 of the string or the -last index and -1 then how on writing above it starts counting from last index whether neither -1 is present at the first place nor the last index so that it starts decreasing 1 from where I can get depth knowledge of working of slicing in python and what does it return like stuff
2 Answers
From the python documentation on slicing sequences like [i:j:k]
The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.
https://docs.python.org/3/library/stdtypes.html#common-sequence-operations
3 Comments
Actually in case of python string slicing it takes three arguments:
[firstArgument:secondArgument:thirdArgument]
FirstArgument consists in the integer value from where the string get sliced.
SecondArgument tells about the up to where the string being sliced.
ThirdArgument tells about that how much step it get jumped
Example:
a="Hello"
print(a[::2])
# outputs 'hlo' without quoting.
slice(None, None, -1). This is given to the__getitem__method of the string object. That method, written in C, takes care to implementation details. EachNoneis interpreted to mean the relevant end point. I don't think we need to know exactly how it does that, just so long as our intuition matches that actual behavior.slice(None,None,-1)we can replace the firstNonewithlen(str), but there's nothing we can use inplace the secondNone.0stops too early.-1means the other end. So we have to trust that the developers have done a good job of handling these 'end point' cases.