17. List Slicing. Please explain it for me


#1

I don't understand how is it working?

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

print message

How do it turn in "I am the secret message!" ?


#2

[::-2] is short for [0:len(garbled):-2] which means in range from first to last index, print reversed str from last one to first one (but jump for one char each time)

to make it easier understanding
[1,2,3,4,5]

[::1]==>[1,2,3,4,5]
[::-1] ==> [5,4,3,2,1]
[::-2]==>[5,3,1]
in the original question, the space count as one char, so it's like this I (jump) Space (jump) a (jump) m


#3

How do it "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI" turn in "I am the secret message!" ?


#4

dont know what you are asking as I already explained how it works before
well....delete all "X" then read backward from last one to first one?


#5

OK. Thank you very much.


#6

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message=filter(lambda x: x!="X", garbled[::-1])


#7

@coremaster73276 reply led me to this solution:

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

#8

How come when i type this coding in.

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

it prints "I am the secret message" and its wrong
but when i change the message to = -2
it prints it backwards and its correct and
when i use
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = filter(lambda x: x != "X", garbled [::-1])
print message
it prints I am the secret message and it's correct.