let's say I have a string:
>>>a = 'akwkwas'
>>>
>>>a[-3:]
'was'
>>>a[-3:None]
'was'
>>>a[-3:0]
''
why can't I use 0
as the end of the slice?
this is from docs:
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
The first row of numbers gives the position of the indices 0...6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.
so when we use negative indices in loop , we should check the end's value, beacuse the end 0
in negative indices does not exist, such as when we split a string to a money-like string:
>>>a = '12349878334'
>>>print(','.join([a[-i-3:-i if i else None] for i in range(0, len(a), 3)][::-1]))
>>>12,349,878,334