1

If there is a string initialized in python:

s="SLICE"

When trying to run this code:

print(s[4::-1])    #Line-1
print(s[4:-1:-1])   #Line2

I thought both are the same thing and give the same output. Instead, Line 1 outputs as expected but Line 2 does not.

jkdev
  • 11,360
  • 15
  • 54
  • 77
  • This is not specified anywhere. How could it be a duplicate question? – Krishna Vamshi Chintala Jun 13 '19 at 19:40
  • I nominated this question for reopening. If it's reopened I'll post an answer. – jkdev Jun 14 '19 at 00:35
  • [As described here](https://stackoverflow.com/a/567094/3345375), slice notation is `s[from:to:step]`. And in a five-character string such as `"SLICE"`, the fifth character `s[4]` is also the last character `s[-1]`. Thus, `s[4]` through `s[-1]` is an empty string, and `s[4:-1:x]` is an empty string for any value of x. – jkdev Jun 14 '19 at 01:07
  • To iterate backwards through the whole string, use this: `s[-1:-6:-1]`. Its starting character is s[-1]. Its ending character is s[-5], which is one step before s[-6] when iterating backwards through the string. Thus, the slice includes the last character through the fifth-to-last character; in other words, the entire five-character string in reverse order. – jkdev Jun 14 '19 at 22:58
  • And as I said, we'll see if the question is reopened. I don't think it's a duplicate. – jkdev Jun 14 '19 at 23:00

0 Answers0