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
  • 228,688
  • 37
  • 348
  • 338
Arindam Roychowdhury
  • 4,939
  • 5
  • 53
  • 57

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
  • 890,778
  • 177
  • 1,125
  • 1,260
1

because st[-1] is 'm':

>>> st="arindam"
>>> st[-1]
'm'
>>> st[::-1]
'madnira'
>>> st[-1::-1]
'madnira'
>>> st[-2::-1]
'adnira'
jcomeau_ictx
  • 36,402
  • 6
  • 91
  • 101