热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

字符串索引-为什么S[0][0]有效且S[1][1]失败?-Stringindexing-WhyS[0][0]worksandS[1][1]fails?

SupposeIcreateastring:假设我创建了一个字符串:>>>SspamNowIindexitasfollows:现在我将其索

Suppose I create a string:

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

>>> S = "spam"

Now I index it as follows:

现在我将其索引如下:

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

I get output as:

我输出为:

>>> 's'

But when i index it as:

但当我将其索引为:

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

I get output as:

我输出为:

Traceback (most recent call last):
File "", line 1, in 
L[1][1][1][1][1]
IndexError: string index out of range

Why is the output not 'p'?

为什么输出不是'p'?

Why also it is working for S[0][0] or S[0][0][0] or S[0][0][0][0] and not for S[1][1] or S[1][1][1] or S[1][1][1][1]?

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

3 个解决方案

#1


10  

The answer is that S[0] gives you a string of length 1, which thus necessarily has a character at index 0. S[1] also gives you a string of length 1, but it necessarily does not have a character at index 1. See below:

答案是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 "", line 1, in 
    S[1][1]
IndexError: string index out of range

#2


8  

The first index ([0]) of any string is its first character. Since this results in a one-character string, the first index of that string is the first character, which is itself. You can do [0] as much as you want and stay with the same character.

任何字符串的第一个索引([0])是它的第一个字符。由于这会产生一个字符的字符串,因此该字符串的第一个索引是第一个字符,它本身就是一个字符。您可以根据需要执行[0]并保持相同的角色。

The second index ([1]), however, only exists for a string with at least two characters. If you've already indexed a string to produce a single-character string, [1] will not work.

但是,第二个索引([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 "", line 1, in 
IndexError: string index out of range

#3


0  

A Python String will always have the 0th Position String / 1st Character. Even if we do [0] 100 times, you are always selecting the 1st character of the remaining string. Thus....

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

For Programming Languages where array subscripts start with 1, you can similarly do this for the 1st Character.

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


推荐阅读
author-avatar
州徐国中
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有