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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With