Why is s [len (s) -1: -1: -1] not working?

When looking at some python lines and functions, I discovered this strange python quirk:

s = "hello" print s[::-1] 

which then prints: olleh

However, print s[len(s)-1:-1:-1] does not work. I understand that it must move from the last element s[len(s)-1] to the first element s[0] . However, it just prints an empty line '' , which, it seems to me, is due to the fact that in lines of some given length (say 5), s[4] == s[-1] . But I don't understand why python decides to use -1 instead of 4 , which is the actual len(s) .

In addition, s[len(s):0:-1] + s[0] works. Why is len(s) valid index? Does Python just convert len(s) to 0 arbitrarily?

PS This is in Python 2.7.8, I'm not sure if it also works in 3.xx

EDIT: Confirmed that Python 3 will be the same

+5
source share
4 answers

The slice designation is as follows:

 s[start:stop:step] 

stop , but not including it. Translate this to what you ask:

 s[len(s)-1:-1:-1] 

This is based on a length of 5 for 'hello'

 s[4:-1:-1] 

or

 s[4:4:-1] 

which is an empty or null string.


I gave a much deeper presentation of slice notation: Explain Python fragment notation

+5
source

Negative indices are counted from the end of the sequence, so you just get [-1:-1:-1] or equivalent to [4:4:-1] , which is a string of zero length.

+2
source

Remember that indexes start with 0, not 1.

[len(s)-1] gets the last letter ( 'o' )

:-1 again just 'o' because you get the last value.

So you want to go from the last value ... to the last value ... reverse ( -1 ). Of course, this will return an empty string.

To answer the second question, this is because there are no errors when using index notation. Try to make print s[32489375:2784:-123]

+1
source

You throw back using the negative step. Default:

from 0 to len (collection) per step

When you use a negative step, indexes must also be canceled, otherwise you will go a long way. For example, from 0 to 5 by -1 goes: 0 + -1 = -1 ; -1 + -1 = -2 ... after some time, overflow of integers occurs ...)

To avoid this long walk around Python, inverts indices when step negative, and treats it as:

from len (collection) to 0 in steps

This means that you need to deal with the start and end values ​​in this case as negative integers from len(collection) - so if you want to get the whole string in the reverse order, you are looking for:

 s[-1:-(len(s) + 1):-1] 

Or simply put:

from {last item in collection} to {first item in collection} by -1

This answer also has a good visual explanation of the indices.

+1
source

Source: https://habr.com/ru/post/1202730/


All Articles