How do you use a variable as an index when slicing strings in Python?
I've been trying to slice two characters out of a string using a loop, but instead of grabbing two characters, it only grabs one.
I've tried:
input[i:i+1]
and
input[i:(i+1)]
but neither seems to work.
How do I use a variable for slicing?
The full routine:
def StringTo2ByteList(input):
# converts d开发者_Go百科ata string to a byte list, written for ascii input only
rlist = []
for i in range(0, len(input), 2):
rlist.append(input[i:(i+1)])
return rlist
The slice values aren't the start and end characters of the slice, they're the start and end points. If you want to slice two elements then your stop must be 2 greater than your start.
input[i:i+2]
A nice way to remember slice indexing is to think of the numbers as labeling the positions between the elements.
So for example to slice ba
you would use fruit[0:2]
. When thinking of it this way, things no longer seem counter-intuitive, and you can easily avoid making off-by-one errors in your code.
Reasoning on the basis of the in-between positions works when we do a left-to-right iteration:
li = [10, 20, 55, 65, 75, 120, 1000]
print 'forward slicing li[2:5] ->',li[2:5]
# prints forward slicing li[2:5] -> [55, 65, 75]
because pos 2 is between 20 / 55 and pos 5 is between 75 / 120
.
But it doesn't work when we do right-to-left iteration:
li = [10, 20, 55, 65, 75, 120, 1000]
print li
print 'reverse slicing li[5:2:-1] ->',li[5:2:-1]
# prints reverse slicing li[5:2:-1] -> [120, 75, 65]
We must think of li[ 5 : 2 : -1 ] as :
from element li[5] (which is 120) as far as uncomprised element li[2] (which is 55)
that is to say
from element li[5] (which is 120) only as far as li[3] included (which is 65) .
.
That makes dangerous reverse slicing from the very end:
li = [10, 20, 55, 65, 75, 120, 1000]
print li[ -1 : 2 : -1 ]
# prints [1000, 120, 75, 65] not [120, 75, 65, 55]
# the same as:
print li[ None : 2 : -1 ]
# prints [1000, 120, 75, 65]
print li[ : 2 : -1 ]
# prints [1000, 120, 75, 65]
and
li = [10, 20, 55, 65, 75, 120, 1000]
print li[ 4 : 0 : -1]
# prints [75, 65, 55, 20] , not [65, 55, 20, 10]
.
In case of difficulty to think like that, a manner to prevent errors is to write
print list(reversed(li[2:5]))
# prints [75, 65, 55]
print list(reversed(li[2:-1]))
# prints [120, 75, 65, 55]
print list(reversed(li[0:4]))
# prints [65, 55, 20, 10]
.
Note that the only way to obtain a reverse slicing as far as the first element INCLUDED is
print li[ 4 : : -1]
that stands for
print li[ 4 : None : -1]
精彩评论