Python - How To Fix String Must Be Indices Error in Python

ID : 27

viewed : 179

Tags : PythonPython StringPython Error

vote vote

98

A string is a collection of characters. In Python, it can be thought of as an iterable of characters.

Every character of a string has a specific index. We can easily access characters at different positions using their indexes.

In this article, Python’s string indices must be integers error. This is a TypeError.

A TypeError occurs in Python when an operation with an invalid data type is performed.

Let us now discuss a situation where this error might occur. See the following code.

a = "SampleString" print(a['e']) 

Output:

TypeError: string indices must be integers 

You can see that the above code raises the discussed error.

We are trying to access an individual character without its index in the above code. As discussed earlier, we need to provide the character’s index within square brackets to achieve this.

See the code below.

a = "SampleString" print(a[5]) 

Output:

e 

The above code returns the character e, since it is at the 6th position.

Note, the first element is stored at the 0th position in Python. The len() function can be used to return the length of the string.

Another situation where we might encounter this error is while performing a string slicing operation. In string slicing, we extract elements between given positions.

We specify the starting and ending positions within the square brackets. Now, let us see the following example.

a = "SampleString" print(a[(5,2)]) 

Output:

TypeError: string indices must be integers 

We pass the indices correctly in the above example, but as a tuple. We need to separate them using a colon : to overcome this error.

For example:

a = "SampleString" print(a[2:5]) 

Output:

mpl 

  • Related HOW TO?