-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 ?

Solen'ya
  • 490
  • 4
  • 11
Jake
  • 15,539
  • 46
  • 120
  • 195

2 Answers2

1

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
  • 14,834
  • 4
  • 27
  • 58
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
  • 652
  • 3
  • 13