-1

I have the following program:

str = 'abcd'
l = len(str)

str2 = str[l-1:0:-1] 

print(str2)

str2 = str[l-1:-1:-1] 

print(str2)

Why does the first print() output dcb and the second print() output an empty string ? Why doesn't the second print() output dcba ?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Jake
  • 16,329
  • 50
  • 126
  • 202

2 Answers2

2

In the statement str[l-1:0:-1] - Last character upto 0th character not including the zeroth element. That's why you get dcb

In the statement str2 = str[l-1:-1:-1] you are going from 3rd index to 3rd index so empty string.

If you need all elements str2 = str[l-1::-1] would give dcba

bigbounty
  • 16,526
  • 5
  • 37
  • 65
0

First case, l=4. You slice abcd from 3 to 0, resulting in dcb. Second case you slice from 3 to -1. -1 is the last element of the list/string. So you are sliciing from 3 to 3, resulting in nothing.

ZWang
  • 832
  • 5
  • 14