If anyone can please explain how the code in red square exactly works.
The top of the page seems to offer a pretty good (and visual!) explanation, really.
What the red box seems to be demonstrating is that you can mix and match postive and negative indices when slicing a string. Even in an otherwise unintuitive way. If you look at the illustration at the top, itâs clear that youâre starting from the -6th element and ending at (but excluding) the 1st (or 2nd, 3rd, and so on) element. Do note that the character at the starting index defined by the slice (here denoted by the negative index) is always included (except when you end up with an empty string) and the character at the ending index defined by the slice is always excluded.
If you think of using negative and postive indices in the opposite order, it does make quite a bit more sense, I feel:
print(word[0:-5])
print(word[0:-4])
print(word[0:-3])
print(word[0:-2])
print(word[0:-1])
that would result in identical output to the one with all negative indices. But it works exactly the same way as the example in red. Youâre selecting one side using a postivie index and the other using the negative index.
With that said, the way this has been used in the red box is unlikely to be useful in practice. If you want a substring from the end of a string, you generally use negative indexing for both the start and the end, just like the block of examples before the red box. Iâve never had the need or desire to use negative indexing in this way. Maybe thereâs some weird edge cases where it makes sense, but Iâve not come across these.
Thanks for the explanation. The reason I had to use it is when I use the negative indexing I cant print the last ânâ I can only print till âPythoâ as end of index is exclusive.
print(word[-6:-1])
So to make it possible in negative indexing it only works with below example which is not making any sense to meâŚ
print(word[-6:6])
If all you want to do is print the last 6 characters, then just omit the end index.
print(word[-6:])
Now, if youâre doing the programatically and youâre ending up wanting to get a slice from -6 to â-0â, then youâve got yourself an edgecase that you need to consider separately.
Assuming youâve got postitive numbers a and b youâve found, where a >= b >= 0 (i.e b can be 0), you could do
word[-a: -b or len(word)]
That way youâd be getting a slice until the end of the word if b == 0 since 0 would evaluate to False in this context.
Or, if you want something more expressive, you could go for
word[-a, -b if b != 0 else len(s)]
or even
word[-a, -b if b != 0 else None]
Bah, you showed all variations except -b or None âŚ
Got to leave something for the imagination! ![]()

