[lower bound : upper bound : step size]
I- Convert upper bound
and lower bound
into common signs.
II- Then check if the step size
is a positive or a negative value.
(i) If the step size
is a positive value, upper bound
should be greater than lower bound
, otherwise empty string
is printed. For example:
s="Welcome"
s1=s[0:3:1]
print(s1)
The output:
Wel
However if we run the following code:
s="Welcome"
s1=s[3:0:1]
print(s1)
It will return an empty string.
(ii) If the step size
if a negative value, upper bound
should be lesser than lower bound
, otherwise empty string
will be printed. For example:
s="Welcome"
s1=s[3:0:-1]
print(s1)
The output:
cle
But if we run the following code:
s="Welcome"
s1=s[0:5:-1]
print(s1)
The output will be an empty string.
Thus in the code:
str = 'abcd'
l = len(str)
str2 = str[l-1:0:-1] #str[3:0:-1]
print(str2)
str2 = str[l-1:-1:-1] #str[3:-1:-1]
print(str2)
In the first str2=str[l-1:0:-1]
, the upper bound
is lesser than the lower bound
, thus dcb
is printed.
However in str2=str[l-1:-1:-1]
, the upper bound
is not less than the lower bound
(upon converting lower bound
into negative value which is -1
: since index
of last element is -1 as well as 3).