0

I was working with some strings and coudn't get myself to understand how the slice works, The following outputs "i"

"input"[0::-1]

whereas the following outputs "tupni"

"input"[::-1]

What I don't get is the first one and how the slicing with negative indices work

sarath joseph
  • 2,533
  • 2
  • 20
  • 23

1 Answers1

3

Maybe these examples will clarify this:

In [146]: "input"[::-1] # from back to the begining. Equivalent to: "input"[len("input")::-1]
Out[146]: 'tupni'

In [147]: "input"[0::-1] # from back to the 0'th (i.e. first) element from back
Out[147]: 'i'

In [148]: "input"[1::-1] # from back to the 2ed element from back
Out[148]: 'ni'

In [151]: "input"[len("input")::-1] # from back to the last element from back (alterantive way)
Out[151]: 'tupni'
Marcin
  • 215,873
  • 14
  • 235
  • 294