Maybe someone can explain why a particular slice operation to reverse
a string doesn’t work. There must be something about slices I don’t
understand. Basic operation: s[start:end:step]
Given
s='abcd'
to reverse this string I can do using default values
s[::-1]
or
s[-1::-1]
Those are fine, but why doesn’t
s[-1:-1:-1]
work and give me the whole string reversed? It should start at with
the last character in the string at (-1), and the stepsize is -1. It should run
down to one before -1 i.e., index 0. Instead I get ”.
for i in xrange(3, -2, -1):
print 's[-1:%d:-1] => ' %i,
print s[-1:i:-1]
yields:
s[-1:3:-1] => # didn't expect any output
s[-1:2:-1] => d
s[-1:1:-1] => dc
s[-1:0:-1] => dcb
s[-1:-1:-1] => # shouldn't this be 'dcba'?
what am I missing here?
(I did see a lot of posting on reversing strings, but if this particular item was explained somewhere I missed it)
Doesn’t work for the same reason that
doesn’t give you ‘abcd’.
When you slice, you are referring to the space between two elements, not the location of those elements. So you’re asking for the space between -1 and -1, which is ”.