-2

I am investigating the slicing of a string with the following code:

s='abcdefgh'
print(len(s))
print(s[-1:-9:-1])
print(s[-8])

whose output is:

8
hgfedcba
a

Why when printing reverse we need to slice till -9 while the last character i.e 'a' at -8?

Heikki
  • 2,214
  • 19
  • 34
Vortex
  • 57
  • 6

2 Answers2

1

That is simply because how indexing works in Python.

s[-1: -9: -1] has 8 characters just like s or s[0: 9: 1] has 8 characters. The last index is always ignored. This is done so that things like range(n) have, like the call suggests, n terms although it goes from 0 to n-1.

It is clearer if you forget numbers altogether and just look at this object: s[0: len(s): +1]. Reverse the sign of the indexes and substract -1 to get the opposite string s[-0-1: -len(s)-1: -1].

Guimoute
  • 4,407
  • 3
  • 12
  • 28
0

In python, slicing can be used to get the sub-section of the Object.

  • len(S) - return the length of the string.
  • S[index] - get the character at a particular index from the start. positive index.
  • S[-index] - get the character at a particular index from the end. negative index.
  • S[start:end] - slice the string from a start index to an end position not index.
  • S[start:] - slice the string from a start index to the last position.
  • S[:end] - slice the string from 0 indexes to the end position.
  • S[:] - get the whole string like copy the string.
  • S[i:j:k] - slice the string with step. default k is +1. like s[2:10:2]
  • s[::-1] - reverse the string.
Sachin Kumar
  • 3,001
  • 1
  • 22
  • 47