>> S[0][0][0][0][0] 我得到的输出是: >>> 's' 但是当我将它索引为: >>> S[1][1][1]-6ren">
gpt4 book ai didi

python - 字符串索引 - 为什么 S[0][0] 有效而 S[1][1] 失败?

转载 作者:太空狗 更新时间:2023-10-30 00:23:24 26 4
gpt4 key购买 nike

假设我创建了一个字符串:

>>> S = "spam"

现在我索引如下:

>>> S[0][0][0][0][0]

我得到的输出是:

>>> 's'

但是当我将它索引为:

>>> S[1][1][1][1][1]

我得到的输出是:

Traceback (most recent call last):
File "<pyshell#125>", line 1, in <module>
L[1][1][1][1][1]
IndexError: string index out of range

为什么输出不是'p'

为什么它也适用于 S[0][0]S[0][0][0]S[0][ 0][0][0] 而不是 S[1][1]S[1][1][1]>S[1][1][1][1]?

最佳答案

答案是 S[0] 给你一个长度为 1 的字符串,因此它必然在索引 0 处有一个字符。S[1] 也给你一个长度为 1 的字符串,但它在索引 1 处不一定有字符。见下文:

>>> S = "spam"
>>> S[0]
's'
>>> S[0][0]
's'
>>> S[1]
'p'
>>> S[1][0]
'p'
>>> S[1][1]
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
S[1][1]
IndexError: string index out of range

关于python - 字符串索引 - 为什么 S[0][0] 有效而 S[1][1] 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33932508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com