当s = 'abcdefg'、s[0:4:-1]和s[1:-1:-1]在Python3中什么都不返回时。但是,s[:4:-1]返回"gf"。有人能解释这两种场景背后的机制(尤其是在内存方面)吗?
发布于 2019-08-30 13:38:03
start始终是迭代的第一个索引。
stop是迭代的结束边界。
step给出了迭代的方向和步骤大小。因此,迭代总是沿着由start符号给出的方向从step到stop。
因此,s[start:stop:step]意味着接受字符s[start]、s[start + step]、s[start + 2 * step]、.等等,直到到达stop为止。
换句话说,s[start:stop:-1]并不等同于reversed(s[start: stop])。
示例
因此,在您的示例s[0:4:-1]中,是step负值,因此迭代过程立即停止,因为start索引已经位于stop.的左边。
a b c d e f g h
0 1 2 3 4 5 6 7
^ ^
s s
t t
a o
r p
t
<-------- orientation另一方面,如果您尝试s[4:0:-1],您将得到'edcb' (请记住,stop索引被排除在外)。
a b c d e f g h
0 1 2 3 4 5 6 7
^ ^
s s
t t
o a
p r
t
<-------- orientation最后,保留start为空意味着从字符串的末尾。这就是为什么从末尾到索引4的所有字符都相反的原因。
a b c d e f g h
0 1 2 3 4 5 6 7
^ ^
s s
t t
o a
p r
t
<-------- orientationhttps://stackoverflow.com/questions/57727463
复制相似问题