Python中的“int(a[::-1])”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31633635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the meaning of "int(a[::-1])" in Python?
提问by sofa_maniac
I cannot understand this. I have seen this in people's code. But cannot figure out what it does. This is in Python.
我不明白这。我在人们的代码中看到了这一点。但无法弄清楚它的作用。这是在 Python 中。
str(int(a[::-1]))
采纳答案by Anand S Kumar
Assuming a
is a string. The Slice notation in python has the syntax -
假设a
是一个字符串。python 中的 Slice 符号具有以下语法 -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
因此,当您这样做时a[::-1]
,它会从末尾开始向第一个取每个元素。所以它反转了a。这也适用于列表/元组。
Example -
例子 -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
然后你把它转换成 int 然后再转换回字符串(虽然不知道你为什么这样做),这只会给你返回字符串。
回答by Abhilash Panigrahi
The notation that is used in
中使用的符号
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
意味着对于给定的字符串/列表/元组,您可以使用格式对所述对象进行切片
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
这意味着该对象将从给定的开始索引中的每个“步骤”索引切片,直到停止索引(不包括停止索引)并将其返回给您。
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
如果缺少起始索引或停止索引,它将采用默认值作为给定字符串/列表/元组的起始索引和停止索引。如果该步骤留空,则它采用默认值 1,即它遍历每个索引。
So,
所以,
a = '1234'
print a[::2]
would print
会打印
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
现在这里的索引和步数都支持负数。因此,如果您给出 -1 索引,则它会转换为 len(a)-1 索引。如果你给 -x 作为步数,那么它会从起始索引开始每 x 个值步进,直到相反方向的停止索引。例如
a = '1234'
print a[3:0:-1]
This would return
这将返回
432
Note, that it doesn't return 4321 because, the stop index is not included.
请注意,它不会返回 4321,因为不包括停止索引。
Now in your case,
现在在你的情况下,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
只会反转存储在字符串中的给定整数,然后将其转换回字符串
i.e "1234" -> "4321" -> 4321 -> "4321"
即“1234”->“4321”->4321->“4321”
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
如果您想要做的只是反转给定的字符串,那么只需 a[::-1] 就可以了。