反转字符串 Python 切片表示法 [英] Reverse string Python slice notation

查看:76
本文介绍了反转字符串 Python 切片表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 切片表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆