0

While I was studying string slicing, skipping of characters of a string and inverting a given string, I stumbled upon the following doubt:

var = 'abcdefghijklmnopqrstuvwxyz'
print(var[-20:-4])          # Works         # '-4' is w
print(var[-4:-20])                          # '-20' is g
print(var[-20:-4:1])        # Works         # '-19' is h
print(var[-20:-4:-1])                       #'-5' is v
print(var[-4:-20:1])
print(var[-4:-20:-1])       # Works

Here out of the 6 print commands, only 3 of them worked and gave an output.

Output:

ghijklmnopqrstuv
(No output just a blank line)
ghijklmnopqrstuv
(No output just a blank line)
(No output just a blank line)
wvutsrqponmlkjih

Q1) Why didn't the other work. Which format works and which doesn't.

Q2) Before this doubt I used to believe that the first 2 numbers (-4 and -20 in this example) were supposed to be entered in ascending order, and that is true as we can see in the very first print command. But then when I try to invert the first command by adding a -1 after the colon, it does not produce any output. What could be the reason behind this?

If you have any other tips on how to invert strings without errors please share.

  • it reads from left to right. ``[-20 : -4]`` means from **g** to **w** in this context: abcdef**g**hijklmnopqrstuv**w**xyz, while the other way around, there is nothing in between – Karina Sep 01 '21 at 11:14
  • 1
    In maths, you can't get from -4 to -20 by only repeatedly adding one, this is no different – Sayse Sep 01 '21 at 11:20
  • https://stackoverflow.com/questions/509211/understanding-slice-notation Yes that does answer my question but I still don't understand one thing. Why does ```a[1::-1] # the first two items, reversed``` the above code give only first 2 items? shouldn't it give all items EXCEPT the first item and reverse them? – Aryan Bansal Sep 01 '21 at 11:23
  • 1
    When the step is negative, the default for ``stop`` is ``-(len+1)``. So these two slices are equal: ``"ABC"[1::-1] == "ABC"[1:-4:-1]`` because ``len("ABC") == 3`` and ``-(3+1) == -4``. And the output is ``BA``: start at 1 (inlcusive) and step -1 from there until we're at -4. – Mike Scotty Sep 01 '21 at 11:39

0 Answers0