I went through the this post about Python string slicing (Reverse string: string[::-1] works, but string[0::-1] and others don't), however still I have some questions. Which takes preference? Is it the index (or indices) for the start/end position? Or the step? Which one is evaluated first?
I have tried few things in Python, and the results are not consistent. See below code / examples. I have put my own analysis in brackets which may be wrong, so please help me correct that as well.
txt="abcdef"
txt[::-1]
result = 'fedcba'
(here the step is given preference, and as it is negative, it starts from the last index, which is 5 or -1, and goes on till the first character 'a')
txt[0:0:-1]
result = '' (seems index are evaluated first. So start at 0 but end before 0, which is not possible, hence no results. Step is not even evaluated.)txt[:0:-1]
result = 'fedcb' (preference is given to step, and then index is considered. So the first index becomes the lat position 'f' and goes till one position before 'a')txt[0::-1]
result = 'a' (I am surprised at this. It seems that start index is given preference here. First index 0 is evaluated as 'a', then the step of '-1' is evaluated. But as nothing more can be accessed because of step '-1', no more characters are printed)
5a. txt[0:1]
result = 'a' (why? default value of step is '1'. Seems start index is evaluated first, 'a' is accessed, printed, and then stops).
5b. txt[0:1:1]
result = 'a' (same as 5a)
5c. txt[0:1:-1]
result = '' (why this? compare this to 5a. Seems that in 5c, step is evaluated first and then start index. If start index would have been evaluated first, atleast 'a' should have been printed).
txt[0:-1:-1]
result = '' (i was expecting 'a' based on preference being given for start index)txt[0::-1]
result = 'a' (now compare this with example 6 above. Why a different result this time? Blank end index is equivalent to reaching right till the end of the string, isn't it?)txt[:len(txt):-1]
result = '' (compare this to 6 and 7)txt[:0:-1]
result = 'fedcb' (seems step is given preference and then the expression is evaluated. And based on step '-1', the start index is evaluated as the last position 'f')
All of this has confused me to say the least.