在 python 中大步切割字符串时的标点符号

Punctuation when slicing string in python with stride

下面的代码,为什么答案中没有'yoif!'感叹号?

>>> s = 'Python is fun!'

>>> s[1:12:3]

>'yoif'

为什么排除感叹号,因为它也有一个索引号,如下代码所示(接上)?

>>> s[13]

>'!'

因为切片就是这样工作的。它将选择索引从 1 开始到最大 12 结束的元素。因此,您看到的唯一元素是索引 1、4、7 和 10。下一步是 13,但由于它高于 12,因此它不会显示。

您的问题本身就提供了答案。您正在从第 1 位到第 12 位(不包括在内)进行切片。所以你会得到第11位的元素。

如果你想获得 ! 将值从 12 更改为 14。请参见下面的代码。

s = 'Python is fun!'
print(s[1:14:3])

输出:

'yoif!'

s = 'Python is fun!'

s[1:12] 只有 returns 字符串直到 'ython is fu' 因此步长 3 无法达到 !

其中

s[1:14] returns 字符串直到 'ython is fun!'.

s[1:14:3] 

输出:'yoif!'

如@Chris_Rands对问题的评论中的linked

a[start:end] # items start through end-1
a[start:]    # items start through the rest of the array
a[:end]      # items from the beginning through end-1
a[:]         # a copy of the whole array

a[start:end:step] # start through not past end, by step

您将 1 定义为切片字符串的开头,将 12 定义为结尾,将 3 定义为步骤。这是切片的一般结构:[start:end:step]

1 开头和 12 结尾,您的字符串如下所示:ython is fu

你必须把你的终点放在正确的位置。所以 s[1:14] 会打印 ython is fun!

当您像这样添加 3 步骤时 s[1:14:3] 您的代码会按您的意愿打印 yoif!

切片,0 索引,格式为[从:最多但不包括:每个]

要包含最后一个元素,请将其从切片中排除并将该部分留空。

>>> "Python is fun!"[1::3] 'yoif!'

将 'from' 留空使其从头开始。

将 'to' 留空使其走到最后。

"Python is fun!"[:] 'Python is fun!'