Python中的扩展切片和字符串

2024-03-28 09:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

>>>"helloworld"[::1]
'helloworld'

>>>"helloworld"[::-1]
'dlrowolleh'

根据语法str[start:end:step]。 在这两种情况下,起始值都默认为0。 在第一种情况下,从索引值0打印字符串。 但在第二种情况下,字符串是从索引值-1打印出来的。在

我的问题是为什么在后面的例子中字符串是从-1打印出来的,为什么是这样?在


Tags: 字符串step语法情况start例子helloworldend
3条回答

扩展切片组件全部默认为无(与简单切片的0和sys.maxint相反):

>>> class A:
...   def __getitem__(self, s):
...     return s
... 
>>> A()[::-1]
slice(None, None, -1)
>>> A()[:]
slice(0, 9223372036854775807, None)

因此,没有自动假定切片应在默认情况下从零开始。在

根据the documentation(着重强调):

The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

这意味着,如果切片步幅为正,则ommited slice start是序列的开始,省略的slice end是序列的结束。如果切片步幅为负,则相反。如果您填写以下两个值之一,则可以看到:

>>> '0123456'[:3]
'012'
>>> '0123456'[:3:-1]
'654'
>>> '0123456'[3:]
'3456'
>>> '0123456'[3::-1]
'3210'

考虑这一点的一种方法是将序列可视化为一个循环,其中起点和终点是同一点。当您省略切片的一端时,您只需指定将这个“两端点”用作端点,而不是指定从那里开始的方向。步幅符号告诉你该走哪条路,这决定了你是把“两端点”当作序列的开始还是结束。在

想象一下

记住切片工作原理的最佳方法是将索引视为指向字符之间的索引,第一个字符的左边缘编号为0。则n个字符组成的字符串最后一个字符的右边缘具有索引n,例如:

 +---+---+---+---+---+ 
 | H | e | l | l | o |
 +---+---+---+---+---+ 
 0   1   2   3   4   5 
-5  -4  -3  -2  -1

指数可以是负数,从右边开始计数。 但请注意-0实际上与0相同,因此它不从右数!在

^{pr2}$

例如,为什么反向索引从-1开始

In [107]: "helloworld"[-1] 
Out[107]: 'd'

用于获取字符串的倒数第二个索引,即[-2],即倒数第二个字符 负步进是必需的,添加该步以到达下一个索引

In [108]: "helloworld"[-1 + -1]
Out[108]: 'l'

相关问题 更多 >