I am just coming cross the following python code which confuses me a bit:
res = self.result[::-1].encode('hex')
The encode stuff is pretty clear, it should be represented as hex value. However, what does this self.result[::-1] mean, especially the colons?
It represents the 'slice' to take from the result. The first element is the starting position, the second is the end (non-inclusive) and the third is the step. An empty value before/after a colon indicates you are either starting from the beginning (
s[:3]
) or extending to the end (s[3:]
). You can include actual numbers here as well, but leaving them out when possible is more idiomatic.For instance:
Return the slice of the string that starts at the beginning and stops at index position 2:
Return the slice of the string that starts at the third index position and extends to the end:
Return the slice of the string that starts at the end and steps backward one element at a time:
Return the slice of the string that contains every other element:
They can all be used in combination with each other as well. Here, we return the slice that returns every other element starting at index position 6 and going to index position 2 (note that
s[:2:-2]
would be more idiomatic, but I picked a weird number of letters :) ):The step element determines the elements to return. In your example, the
-1
indicates it will step backwards through the item, one element at a time.That's a common idiom that reverses a list.
You can read about 'extended slices' here.