I just started learning programming and I need some clarification.
For
s = "abcdef"
print(s[0:2:-1])
The output is an empty string. What I don't quite understand is why print(s[:2:-1])
has an output of fed, and print(s[0:2:-1])
does not.
I just started learning programming and I need some clarification.
For
s = "abcdef"
print(s[0:2:-1])
The output is an empty string. What I don't quite understand is why print(s[:2:-1])
has an output of fed, and print(s[0:2:-1])
does not.
print(s[:2:-1])
is not the same as print(s[0:2:-1])
- it's the same as print(s[None:2:-1])
. When you leave out one of the slice parameters or use None
, the endpoint is substituted. If the step size is negative, the start point is the end of the sequence and the end point is the start of the sequence. print(s[0:2:-1])
goes from s[0]
to s[2]
, but it can't because 2 > 0
and there's no way to count backward from 0 to 2. print(s[:2:-1])
goes from s[-1]
to s[2]
, because s[-1]
is the last character of the string.
If you set the third parameter to be negative, the elements of the iterable will be traversed in reverse order. Then letting the first parameter be empty will mean that the iteration should start from the rightmost element. Think about the fact that s[::-1] == 'fedcba'
.
I will explain what those three numbers in the indexing mean!
s = "abcdef"
In this string, indexing start with 0
if you are counting from left and with -1
if you are counting from right. That means, if you start counting from left, a
is indexed as 0
and f
is indexed as 5
and if you count from right, f
is indexed as -1
and a
is indexed as -6
.
Hence
>>> s[0:-1]
'abcde'
If you want indexes with constant separation, then you can introduce one more number after the start and end as shown below.
>>> s[0:5:2]
'ace'
This means , you are reading from start to end every 2
nd index. Furthermore, when you write
>>> s[::-1]
'fedcba'
You are referring every -1
th index which essentially means, yeah! you guessed it :) , reversing the order!
I think this answer along with other answers in this thread should give you a good idea!
Regards
The syntax of string slice is simple:
x[start:end:step]
where the slice starts at start
and ends before end
, iterating by step
.
s[0:2:-1]
returns []
because you can't slice from index 0 to 2 backwards. It makes no sense! s[2:0:-1]
(which returns 'cb'
) would make more sense.
s[:2:-1]
returns 'fed'
. Leaving out the start
and a step
of -1 implies a slice from the end of the sequence up to index 2 in reverse (since step
is -1).