Python 字符串索引-为什么S[0][0]工作而S[1][1]失败?

Python 字符串索引-为什么S[0][0]工作而S[1][1]失败?,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,假设我创建了一个字符串: >>> S = "spam" 现在我将其索引如下: >>> S[0][0][0][0][0] 我得到的输出是: >>> 's' Traceback (most recent call last): File "<pyshell#125>", line 1, in <module> L[1][1][1][1][1] IndexError: string index out of range

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

>>> S = "spam"
现在我将其索引如下:

>>> S[0][0][0][0][0]
我得到的输出是:

>>> 's'
Traceback (most recent call last):
File "<pyshell#125>", line 1, in <module>
L[1][1][1][1][1]
IndexError: string index out of range
但当我将其索引为:

>>> S[1][1][1][1][1]
我得到的输出是:

>>> 's'
Traceback (most recent call last):
File "<pyshell#125>", line 1, in <module>
L[1][1][1][1][1]
IndexError: string index out of range
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
L[1][1][1][1]
索引器错误:字符串索引超出范围
为什么输出不是“p”


为什么它也为S[0][0]S[0][0][0]S[0][0][0]工作,而不是为S[1][1]S[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
>S=“垃圾邮件”
>>>S[0]
's'
>>>S[0][0]
's'
>>>S[1]
“p”
>>>S[1][0]
“p”
>>>S[1][1]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
S[1][1]
索引器错误:字符串索引超出范围
任何字符串的第一个索引(
[0]
)是它的第一个字符。因为这会产生一个单字符字符串,所以该字符串的第一个索引是第一个字符,即它本身。您可以随心所欲地执行
[0]
,并保持相同的角色

但是,第二个索引(
[1]
)仅适用于至少包含两个字符的字符串。如果已为字符串编制索引以生成单个字符串,
[1]
将无法工作

>>> a = 'abcd'
>>> a[0]
'a'
>>> a[0][0]
'a'
>>> a[1]
'b'
>>> a[1][0][0]
'b'
>>> a[1][1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>a='abcd'
>>>a[0]
“a”
>>>a[0][0]
“a”
>>>a[1]
“b”
>>>a[1][0][0]
“b”
>>>a[1][1]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
索引器错误:字符串索引超出范围

Python字符串将始终具有第0位字符串/1个字符。即使我们执行[0]100次,您也总是选择剩余字符串的第一个字符。因此


对于数组下标以1开头的编程语言,同样可以对第一个字符执行此操作。

S[0]
是“S”,而
“S”[0]
是“S”,而
“S”[0]
是“S”,而
“S”[0]
是“S”,而
“S”[0]
是“S”,等等。但是
“s”[1]
是不受限制的,因为“s”只有一个聊天,即“s”,并且它在0索引中。我觉得我们几乎完全按照相同的命令顺序进行操作很有趣。:)