python - 在Python中使用负数对字符串进行切片时,0被禁用?

标签 python python-2.7 python-3.x

假设我有一个字符串:

>>>a = 'akwkwas'
>>>
>>>a[-3:]
'was'
>>>a[-3:None]
'was'
>>>a[-3:0]
''

为什么我不能使用 0 作为切片的结尾?

这是来自文档:

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

所以当我们在循环中使用负索引时,我们应该检查结尾的值,因为负索引中的结尾 0 不存在,例如当我们将字符串拆分为类似金钱的字符串时:

>>>a = '12349878334'
>>>print(','.join([a[-i-3:-i if i else None] for i in range(0, len(a), 3)][::-1])) 
>>>12,349,878,334

最佳答案

0序列的开始。总是,毫不含糊。将其含义更改为有时是结束会导致很多混淆,尤其是在为这两个值使用变量时。

使用负索引也不是一个不同的模式;负索引被转换为相对于长度的正索引。因为 other 切片输入(开始或停止)是负数而更改元素 0 是没有意义的。

因为 0 始终表示序列的第一个元素,并且没有负零的拼写,所以您不能使用 0 表示序列的结尾。

如果您需要参数化您的索引,您可以使用 None 作为 stop 元素来代替:

start = -3
stop = None
result = a[start:stop]

您还可以创建 slice() object ;相同的规则适用于索引的解释方式:

indices = slice(-3, None)
result = a[indices]

实际上,解释器将切片表示法翻译成一个slice()对象,然后将其传递给该对象,以区别于使用单个整数的直接索引; a[start:stop] 符号转换为 type(a).__getitem__(a, slice(start, stop))a[42] 变为 type(a).__getitem__(a, 42)

因此,通过使用 slice() 对象,您可以使用单个变量记录切片或单元素索引。

关于python - 在Python中使用负数对字符串进行切片时,0被禁用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31740252/

相关文章:

python - 如何在 Python 中查找空列表的所有索引

python - Homebrew python 公式 pip 安装

python - 在 Python 3 中调用 dict.keys() 的复杂度是多少?

python - Tkinter 回调中的奇怪异常

python - 找不到 pyinstaller 添加数据文件

Python 日志记录 : propagate messages of level below current logger level

python - 适当的相对进口 : "Unable to import module"

python-3.x - Python 3.5 类变量

javascript - 在 Bokeh 服务器配置中如何从客户端浏览器获取 x,y 坐标到服务器

python - pygame 移动用户控制的对象直到释放键?