对于以下代码,为什么答案不是“yoif!” 带感叹号?
>>> s = 'Python is fun!'
>>> s[1:12:3]
>'yoif'
为什么不包括感叹号,因为它也有一个索引号,如以下代码所示(接上)?
>>> s[13]
>'!'
对于以下代码,为什么答案不是“yoif!” 带感叹号?
>>> s = 'Python is fun!'
>>> s[1:12:3]
>'yoif'
为什么不包括感叹号,因为它也有一个索引号,如以下代码所示(接上)?
>>> s[13]
>'!'
您定义1
为切片字符串的开头,12
结尾和3
步骤。这是切片的一般结构:[start:end:step]
以 开头1
和结尾12
,您的字符串如下所示:ython is fu
你必须把你的终点放在正确的位置。所以s[1:14]
会打印ython is fun!
当您添加3
这样的步骤时,s[1:14:3]
您的代码会按照您的意愿打印yoif!
。
因为这就是切片的工作原理。它将选择索引从 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]
只返回字符串,直到'ython is fu'
无法达到 3 的步幅!
然而
s[1:14]
返回字符串直到'ython is fun!'
。
s[1:14:3]
输出:'yoif!'
正如@Chris_Rands 对问题的评论中所链接的:
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
切片,索引为 0,格式为 [from : up to but not include : every]
要包含最后一个元素,请将其从切片中排除,并将该部分留空。
>>> "Python is fun!"[1::3]
'yoif!'
将'from'留空使其从头开始。
将'to'留空会使它走到最后。
"Python is fun!"[:]
'Python is fun!'