String indexing - Why S[0][0] works and S[1][1] fails?

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 "<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 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]?

1

3 Answers

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 = "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
0

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.

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.

>>> 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
1

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....

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like