2

I understand that when slicing strings, the first index number refers to the start (inclusive), second number refers to end (exclusive) and the third refers to step size. So, wouldn't the first example throw an index error since length 6 is outside of the string? In the second example I would've expected "nohty" and "ohty" for the third example but this is clearly not the case.

temp = 'Python'
stringLen = len(temp)
slicedStr = temp[stringLen::-1]
print(slicedStr)
>>> nohtyP

stringLen = len(temp) - 1
slicedStr = temp[stringLen::-1]
print(slicedStr)
>>> nohtyP

stringLen = len(temp) - 2
slicedStr = temp[stringLen::-1]
print(slicedStr)
>>> ohtyP
user6235442
  • 136
  • 7
  • I would suggest look here then the duplicate link: https://stackoverflow.com/questions/9490058/why-does-substring-slicing-with-index-out-of-range-work – Boendal Dec 31 '19 at 05:40

1 Answers1

0

Try this

print(temp[-1::-1])

now the first index will point to the last character.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Shashikumar KL
  • 1,007
  • 1
  • 10
  • 25