Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 data 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
like image 506
Lance Roberts Avatar asked Dec 04 '22 20:12

Lance Roberts


2 Answers

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]
like image 142
Ignacio Vazquez-Abrams Avatar answered Feb 20 '23 00:02

Ignacio Vazquez-Abrams


A nice way to remember slice indexing is to think of the numbers as labeling the positions between the elements.

slice example

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.

like image 23
wim Avatar answered Feb 19 '23 23:02

wim