0

This has been asked many times but i do not want to ask that again . I just want to know how is this happening ?

>>> st="arindam"

>>> st[::-1]   #This is the one that everyone probably uses 
'madnira' 

Would someone please explain why this works?

>>> st[-1::-1]
'madnira'

How is this also reversing the string successfully? I thought this would start from 'a' and print 'adnira'

larsks
  • 277,717
  • 41
  • 399
  • 399
Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63

2 Answers2

4

In Python list indexes, the index -1 refers to the last character in the string. When using a negative step index, omitting the start index uses -1 as the start (a positive step index starts at 0 by default).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

because st[-1] is 'm':

>>> st="arindam"
>>> st[-1]
'm'
>>> st[::-1]
'madnira'
>>> st[-1::-1]
'madnira'
>>> st[-2::-1]
'adnira'
jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107