>> S[0]...">

String Indexing - Why does S [0] [0] work and S [1] [1] fails?

Suppose I create a line:

>>> S = "spam" 

Now I index it as follows:

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

I get output like:

 >>> 's' 

But when I index it like:

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

I get output like:

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

Why is the output not 'p' ?

Why does it work 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] ?

+5
source share
3 answers

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

 >>> 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 
+10
source

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

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

 >>> 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 
+8
source

A Python string will always have the 0th position of a String / 1st Character. Even if we do [0] 100 times, you always select the 1st character of the remaining line. In this way....

For programming languages, where array indices begin with 1, you can do this for the 1st character in the same way.

0
source

Source: https://habr.com/ru/post/1236877/


All Articles