17. List Slicing help


#1

Hey guys. Just a quick question. I was wondering what the difference is between the two codes below.

Upon trying the first one, it would say that the output is "" instead of the correct answer (printing every second letter backwards).
However when I try [::-2] I got the answer. I'm confused as to why the first one didn't give me the solution (or return anything at all).

Can someone explain why the first script didn't work??

Thanks.


garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[0:len(garbled):-2];
print message; 

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2];
print message;


#2

what is with all the semi-colons? This is python, not javascript

so, list slicing:

[start:end:steps]

you know this right? so you start at 0, you end at len garbled with steps of -2. But 0 is already less then len garbled, so nothing will happen, you need to start at the end of string:

garbled[len(garbled):0:-2]

however, the 0 is a bit of a problem, because it is not included. so ! is missing, you might want to leave it out


#3

This was my solution

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-1]
message = message[::2]
print message

First: Reverse the message.
Second: We want every second letter in the message

Hope it helps


#4

your 2nd line change the stride from -2 to -1 and remove the semi-colons that should work.