Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

python - What does 'result[::-1]' mean?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

In [1]: s = 'abcdefg'

Return the slice of the string that starts at the beginning and stops at index position 2:

In [2]: s[:3]
Out[2]: 'abc'

Return the slice of the string that starts at the third index position and extends to the end:

In [3]: s[3:]
Out[3]: 'defg'

Return the slice of the string that starts at the end and steps backward one element at a time:

In [4]: s[::-1]
Out[4]: 'gfedcba'

Return the slice of the string that contains every other element:

In [5]: s[::2]
Out[5]: 'aceg'

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 :) ):

In [6]: s[6:2:-2]
Out[6]: 'ge'

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...