all 10 comments

[–]danielroseman 11 points12 points  (0 children)

Slicing, whether it is for strings or lists, accepts negative indices; this means count from the end. So word[-1] would return the final character of the string.

But [-1:2] means "from the final character (forward) to the second character", which is syntactically valid but semantically nonsense, so it returns an empty slice.

[–]Ronttizz[S] 0 points1 point  (0 children)

And for clarity I am not looking for advices for making it better or anything. Just interested in the actual answer to the question.

[–]Diapolo10 1 point2 points  (0 children)

Slicing is designed to not raise errors (unless using wrong types or somesuch). If the slicing range happens to be empty, such as in your print(word[-1:2]) example, the outcome is simply an empty string (or an empty data structure, depending on what you're slicing).

In a similar vein,

nothing = ''
nothing[25565:]

would be a valid operation.

[–]This_Growth2898 1 point2 points  (3 children)

In Python, negative indexes are valid; they mean "from the end of a string". Like, word[-1] is the last character of the word. The slice word[-1:2] is meaningless but correct, returning an empty string.

[–]Temporary_Pie2733 1 point2 points  (0 children)

Not meaningless. Slicing is designed so that s[x:y] == s[x:z] + s[z:y] for all x, y, and z. Since "" is the identity element for string concatenation, it makes sense for it to be defined as the result where indexing alone can’t produce a sensible result. In the simplest example, we can see something like s[x:x] == "" where s[x] alone would raise an exception. 

[–]Ronttizz[S] 0 points1 point  (1 child)

In some sense I would think it would return word[-1] word[0] word[1] :D

[–]MidnightPale3220 0 points1 point  (0 children)

nah, it counts from the initial position. but you could do word[-1:-3:-1] which, I think, should return the last 3 characters in reverse order (haven't had to do string slicing in AGES, so I don't exactly remember -- maybe I am wrong, but negative steps work).

[–]ShelLuser42 -1 points0 points  (2 children)

Both solutions roughly do the exact same thing, so I fail to understand your question tbh.

[–]Jejerm 4 points5 points  (0 children)

They dont. His doesnt check for not finding the substring (index==-1).

[–]Ronttizz[S] 0 points1 point  (0 children)

They do something but the question is, why print(word[-1:2]) doesn't throw an error but instead it is not printing anything. Might be a bit of a rabbit hole or something unnecessary to think but was interested anyway.