I've read with interest Understanding slicing and What does 'result[::-1]' mean?
>>> a = 'Python'
# a[start:stop:step] with start and stop inverted if stem < 1
>>> a[::-1]
'nohtyP'
I got that:
>>> a[::-1] == a[None:None:-1]
True
But I still asking to myself the following question:
Why I cant create with some default start
stop
values the equivalent of a[::-1]
?
>>> a[len(a):0:-1]
'nohty'
>>> a[len(a) 1:0:-1]
'nohty'
>>> a[len(a) 1:-1:-1]
''
Can I catch the P
of Python with explicit indices ?
CodePudding user response:
You can reverse the string with explicit indices if you use negative indices
print(a[-1:-len(a)-1:-1]) # nohtyP
CodePudding user response:
I think not because the stop
value in the slice is not included in the slice.
You are looking for a stop
value that includes P, in other words includes index 0. However that is not possible due to how python uses negative numbers in slices.
a[-1:0:-1] -> 'nohty'
We would expect to get P if we go down by one from 0, use -1, but -1 is interpreted as last index, hence the string will be empty.
a[-1:-1:-1] -> ''
TL;DR: nope, not possible