问题描述
string = "HELLO"
print string[::-1] #as expected
print string[0:6:-1] #empty string why ?
我很惊讶地看到在 python 中反转字符串是多么容易,但后来我发现了这一点并迷路了.有人可以解释为什么第二个反向不起作用吗?
I was amazed to see how easy it is to reverse a string in python but then I struck upon this and got lost. Can someone please explain why the second reverse does not works ?
推荐答案
切片符号的写法如下:
list_name[start_index: end_index: step_value]
python 中的列表索引与数轴上的数字不同.当step_value
为-1
时,列表索引不会在0th
索引之后转到-1st
.
The list indexes in python are not like the numbers present on number line. List indexes does not go to -1st
after 0th
index when step_value
is -1
.
因此产生以下结果
>>>>打印字符串[0:6:-1]
>>>>
还有
>>>>打印字符串[0::-1]
>>>>H
所以当 start_index
为 0 时,它不能以循环顺序遍历索引到 -1, -2, -3, -4, -5, -6 for step_value
是 -1
.
So when the start_index
is 0, it cant go in a cyclic order to traverse the indexes to -1, -2, -3, -4, -5, -6 for step_value
is -1
.
同样
>>>>打印字符串[-1:-6:-1]
>>>>OLLEH
和
>>>>打印字符串[-1::-1]
>>>>OLLEH
还有
因此,当 start_index
为 -1 时,它会以循环顺序遍历索引到 -1、-2、-3、-4、-5、-6 以给出输出 OLLEH
.
thus when the start_index
is -1 it goes in a cyclic order to traverse the indexes to -1, -2, -3, -4, -5, -6 to give output OLLEH
.
当 start_index
为 6 并且 step_value
为 -1 时,很容易理解
Its pretty straight forward to understand when start_index
is 6 and step_value
is -1
>>>>打印字符串[6::-1]
>>>>OLLEH
这篇关于反转字符串 Python 切片表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!