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]?
The “TypeError: string index out of range” error is raised when you try to access an item at an index position that does not exist. You solve this error by making sure that your code treats strings as if they are indexed from the position 0.
The string index out of range means that the index you are trying to access does not exist. In a string, that means you're trying to get a character from the string at a given point. If that given point does not exist , then you will be trying to get a character that is not inside of the string.
Because strings, like lists and tuples, are a sequence-based data type, it can be accessed through indexing and slicing.
String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on. The index of the last character will be the length of the string minus one. For any non-empty string s , s[len(s)-1] and s[-1] both return the last character.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With