Reputation: 3245
If you define a string in Python like:
x = "1234567890"
print(x[::-1])
prints the string in reverse order, but
print(x[0:10:-1])
prints nothing.
Why don't they print the same thing?
Upvotes: 1
Views: 1726
Reputation: 1493
You should know about the basic rule x[start:stop:step]
. In your code, you put two different rules: print(x[0:10:-1])
and print(x[::-1])
.
When you put nothing in the start
and stop
index, your code will be executed using the default depends on the step. If the step is positive, then the start
index will be from 0
and the stop
is the length of the string. Here, you may customize the start
and stop
value as long as they fulfilling start < stop
.
On the other hand, if the step is negative, then the start
index will be from the last index of the string while the stop
is 0
. Here, you may also customize the start
and stop
value as long as they fulfilling start > stop
.
In your case, you wrote print(x[0:10:-1])
that gives you nothing back. This clearly because you set 0
as the start and 10
as the stop index while the step is negative.
Reference: https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3
Upvotes: 1
Reputation: 512
You are looking for print(x[10:0:-1])
.
>>> x = list(range(10))
>>> x[10:0:-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
We can model x[start:end:step]
with the following pseudocode:
i = start
if start < end:
cond = lambda: i < end
else:
cond = lambda: i > start
while cond():
SELECT x[i]
i += step
Upvotes: 0
Reputation: 19885
See note 5 of the relevant docs:
The slice of s from i to j with step k is defined as the sequence of items with index
x = i + n*k
such that0 <= n < (j-i)/k
. In other words, the indices arei
,i+k
,i+2*k
,i+3*k
and so on, stopping when j is reached (but never including j)
Accordingly, when you specify i = 0, j = 10, k = -1
in [0:10:-1]
, there are no values of n
which satisfy the equation 0 <= n < (j-i)/k
, and therefore the range is empty.
On the other hand, in [::-1]
, i == j == None
. Refer to the next part of note 5:
If i or j are omitted or None, they become “end” values (which end depends on the sign of k).
Since k
is negative, i
becomes len(s) - 1
, which evaluates to 9
. j
cannot be represented by any number (since 0
would cut off the last character).
Upvotes: 3