+ 2

# Can someone explain this string slicing?

a = "Hello Everyone" print(a[0 : -10 : -1]) Output ' ' print(a[0 : -100 : -1) Output 'H'

3 Answers

+ 6

From the documentation for string slicing,
"out of range slice indexes are handled gracefully when used for slicing"
word = "Python"
print(word[4:42]) # on
print(word[42:]) #""
Also, correct syntax for negative slicing
a[start:stop:step], start < stop

+ 1

a[start : end : step]
I think we can simply do some tests.
1. start and end indicate the index "range" from start to end
>>> a[0: 10]
'Hello Ever'
>>> a[0]
'H'
>>> a[10]
'y'
We got that the range doesn't include the end one.
2. what's the negative sign mean in the index ?
>>> a[-1]
'e'
>>> a[-2]
'n'
-1 points to the last of the list, -2 the second to last, and so on.
We list and count them.
H 0 -14
e 1 -13
l 2 -12
l 3 -11
o 4 -10
5 -9
E 6 -8
v 7 -7
e 8 -6
r 9 -5
y 10 -4
o 11 -3
n 12 -2
e 13 -1
so a[-1] equal a[13], a[-2] equal a[12]
a[0: -13] equal from 0 to 1
>>> a[0:1]
'H'
a[0: -14] equal from 0 to 0
>>> a[0:0]
''
It's empty, why?
3. The default start and end
>>> a[:2]
'He'
>>> a[0:2]
'He'
>>> a[0:]
'Hello Everyone'
>>> a[0:13]
'Hello Everyon'
>>> a[0:14]
'Hello Everyone'
We assume that the default start is 0, and the default end is len(a)
4. What will happen if we pass a start index really greater than the end ?
>>> a[10: 0]
''
>>> a[1: 11]
'ello Every'
a[10: 0] expected "yrevE olle", but it's empty, why?
We thought the default "direction" like 10 9 8 .. 1, from start to end, decreased
a[1: 11] tells us that the true default "direction" is 1 2 3 .. 10, increased
a[10: 0], would be 10 11 12.. ?, but our "range" is 10 9 8 .. 1, incompatible
5. Then how to adjust the direction ? step
>>> a[10: 0: -1] # range 10 9 8 .. 1, direction 10 9 8 .. 1, step 10 9 8 .. 1
'yrevE olle'
>>> a[10: 0: -2] # range 10 9 8 .. 1, direction 10 9 8 .. 1, step 10 8 6 .. 2
'yeEol'
>>> a[1: 11: 1] # range 1 2 3 .. 10, direction 1 2 3 .. 10, step 1 2 3 .. 10
'ello Every'
We got that the default step is 1, and step means an interval, and the step's negative sign a direction.
>>> a[10: 0: 1] # range 10 9 8 .. 1, direction 10 11 12.., step 10 11 12.., where is the end?
''
>>> a[1: 11: -1]# range 1 2 3 .. 10, direction 1 0 -1 -2 -3 -4, step 1 0 -1 -2 -3 -4
''
If we follow the previous logic, a[1: 11: -1] go until meet the

+ 1

>>> a = "Hello Everyone"
>>> b = slice(0, 10, 1)
>>> c = b.indices(len(a))
>>> list(range(*c))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = slice(10, 0, 1)
>>> c = b.indices(len(a))
>>> list(range(*c))
[]
>>> b = slice(1, 11, -1)
>>> c = b.indices(len(a))
>>> list(range(*c))
[]
>>> b = slice(0, -100, -1)
>>> c = b.indices(len(a))
>>> list(range(*c))
[0]
>>> b = slice(0, -10, -1)
>>> c = b.indices(len(a))
>>> list(range(*c))
[]