Why does [-1: -1: -1] not work to change the line?

Can someone explain why a particular operation to cut a string does not work. There must be something about slices that I don’t Understand. The main operation: s [start: end: step]

Considering

s='abcd'

to cancel this line i can use the defaults

s[::-1]

or

s[-1::-1]

All right, but why not

s[-1:-1:-1]

work and give me the whole chain in reverse order? It should begin with the last character in the string at (-1), and the step is -1. It should work up to one to -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]

gives:

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 saw a lot of messages about return lines, but if this subject was explained somewhere, I missed it)

+3
source share
6 answers
s[-1:-1:-1]

Doesn't work for the same reason that

s[0:0]

"abcd".

, , . , -1 -1, '..

+6

>>> s[-1:-1:-1]
>>> ''

start end -1, . start end, step . end, ... ''.

Try:

>>> s[1:1:1]
>>> ''

, , .

+3

:

  • ;
  • .

, , , , , , :

-1, .. 0

+3

[start:end:stride] - ,

, , , , , . , , .

+1

, -1 , " " . .

, , Python -1, " " 0 . . , , :

'abcd'[-2:-1:-1] == 'cbad'

. .

>>> 'abcd'[-2:-1:-1] 
''

The correct interpretation of negative indexes in row slicing is inverse indexing from the end of the line, and not circular indexing from 0.

For additional thought, consider the following:

a = 'abcd'
a[-1:-(len(a) + 0):-1] == 'dcb'
a[-1:-(len(a) + 1):-1] == 'dcba'
a[-1:-(len(a) + 2):-1] == 'dcba'
+1
source

So miserable, right? Here's an inconvenient workaround.

for i in range(3, -2, -1):
    j = i if i != -1 else None
    print 's[-1:%s:-1] => ' % str(j),
    print s[-1:j:-1]

s[-1:3:-1] =>  
s[-1:2:-1] =>  d
s[-1:1:-1] =>  dc
s[-1:0:-1] =>  dcb
s[-1:None:-1] =>  dcba

Here the variation is the same. I am not sure if this will be less inconvenient.

for i in range(3, -1, -1) + [None]:
    print 's[-1:%s:-1] => ' % str(i),
    print s[-1:i:-1]

s[-1:3:-1] =>  
s[-1:2:-1] =>  d
s[-1:1:-1] =>  dc
s[-1:0:-1] =>  dcb
s[-1:None:-1] =>  dcba
+1
source

All Articles