×

Python TypeError

What is TypeError in python?

TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can say not a valid object type.

  • It is raised or occurs whenever there is an exception.
  • Also, as the name suggests, this type of error arises whenever there is a wrong object, and we perform an unrelated operation on it.
  • There are mainly three types of errors in the Python programming language: syntax error, logical error, and exception.
  • This type of error lies in the category of exception error.
  • The user can easily handle the type error using the raise keyword.

TypeError: string indices must be an integer

  • As we all know, the basic structure of the string consists of index values.
  • The starting value of the string begins with the index value 0, and it will continue till the length of the given string.
  • TypeError arises whenever we want to fetch out the particular character of the string with the specified index value. Still, instead of entering the integer value in the index, we will enter another value of a different object type.
  • For example, if we want to fetch character 2 from the string, we enter the index as an integer instead of an integer, which will raise a type error string indices must be an integer.

Let us understand it with the help of examples:

Examples of TypeError: String indices must be an integer

Example 1: Given a string named “ JavaTpoint ” and you are required to fetch out the particular character “ T ”  from it.

(Here, we will discuss all the cases in which the type error arises for the above example, along with its solution.)

Case 1: We pass the number in string format instead of an integer value in the index.

# Python program to fetch the particular character from the string


print("Enter a string: ")                                      # Enter string JavaTpoint
s=input()
print("To fetch out the character 'T'  from the string")
s["4"]                                                              # As the string begans with index value 0,        
# after onwards it will go further by adding 1 to it.

Explanation:

In the above case, if we observe that, it generates a type error: string indices must be an integer because, to fetch out the character ‘ T 'from the alphabet JavaTpoint, we have to pass the index value 4 in integer form instead of a string.

Here, we pass the value 4 but not in the integer form, but in the string form as we have assigned it in double-quotes.

The output of case 1:

TypeError string indices must be an integer

Let us understand it in detail, with the help of the correction mentioned below:

Correction of case 1:

# Python program to fetch the particular character from the string


print("Enter a string: ")                                      # Enter string JavaTpoint
s=input()
print("To fetch out the character 'T'  from the string")
s[4]                                                              # As the string begins with index value 0,        
# after onwards it will go further by adding 1 to it.

The output of the correction of case 1:

TypeError string indices must be an integer

Case 2: We pass the index's string value instead of an integer value.

# Python program to fetch the particular character from the string


print("Enter a string: ")                                      # Enter string JavaTpoint
s=input()
print("To fetch out the character ' o '  from the string")
s[‘o’]                                                              # As the string begans with index value 0,        
# after onwards it will go further by adding 1 to it.

Explanation:

In the above case, if we observe that, it is generating a type error: string indices must be an integer because, here, to fetch out the character ‘ o ', from the alphabet JavaTpoint, we have to pass the index value 6 in integer form instead of a string.

Here in the above program, we pass the alphabet directly rather than the integer value, but in the string form as we have assigned it in double-quotes.

Let us understand it in detail, with the help of the correction mentioned below:

The output of case 2:

TypeError string indices must be an integer

Correction of case 2:

# Python program to fetch the particular character from the string


print("Enter a string: ")                                      # Enter string JavaTpoint
s=input()
print("To fetch out the character ' o '  from the string")
s[6]                                                              # As the string begins with index value 0,        
# after onwards it will go further by adding 1 to it.

The output of the correction of case 2:

TypeError string indices must be an integer

Example 2: Given a string named “ Wonderful ” and you are required to fetch out the particular slice from the string or can say a part of string “ der ”  from it, which we called string slicing.

Case 1: We pass the number in string format instead of an integer value in the index.

# Python program to fetch the particular part from the string


print("Enter a string: ")                                      # Enter string Wonderful
s=input()
print("To fetch out the particular slice ' der '  from the string")
s["3":"6"]                                                              # As the string begans with index value 0,        
# after onwards it will go further by adding 1 to it.

Explanation:

In the above case, it is generating a type error: string indices must be an integer because, here, to fetch out the particular part of the string ‘ der ’, from the alphabet Wonderful, we have to pass the index value 3: 6 in integer form instead of a string.

In the above program, we need to pass the value 3: 6 not in the integer form, but in the string form as we have assigned it in double-quotes.

The output of case 1:

TypeError string indices must be an integer

Let us understand it in detail, with the help of the correction mentioned below:

Correction of case 1:

# Python program to fetch the particular part from the string


print("Enter a string: ")                                      # Enter string Wonderful
s=input()
print("To fetch out the particular slice ' der '  from the string")
s[3:6]                                                              # As the string begans with index value 0,        
# after onwards it will go further by adding 1 to it.

The output of the correction of case 1:

TypeError string indices must be an integer

Example 3: For a dictionary example, we have given a dictionary set from which we are required to fetch out the particular key with its corresponding value from the dictionary.

Case 1: When we pass the string value in the index, instead of the integer value

# Python program to fetch out the particular key with its corresponding value


d1 = { "Shivani" : 19, "Sneha" : 31, "Preeti" : 8, "Abhi" : 50}   # declaring a dictionary
for i in d1:
  print("Sneha: " + i["Sneha"])
  print("Abhi: " + i["Abhi"])

In the above case, it is generating a type error: string indices must be an integer because, here to fetch out the particular key say “ Sneha ”, from the dictionary d1, we have to pass the index i, which already in integer form instead of a string.

Here in the above program, we pass the string directly rather than the integer value, but in the string form as we have assigned it in double-quotes.

The output of case 1:

TypeError string indices must be an integer

Let us understand it in detail, with the help of the correction mentioned below:

Correction of case 1:

# Python program to fetch out the particular key with its corresponding value


d1 = { "Shivani" : 19, "Sneha" : 31, "Preeti" : 8, "Abhi" : 50}   # declaring a dictionary
for i in d1:
  print(i)

The output of the correction of case 1:

TypeError string indices must be an integer

Handling TypeError: String indices must be an integer

In the above examples, we saw that typeError could be generated when we enter the string in the wrong format other than integer values. Although we have seen the correction of all the examples, we must know how to handle all such exceptions.

To handle these exceptions in the python programming language, we will generally use the ' try ' and ' except ' keyword, try block. We will enter all the test cases, which are mainly as much as possible, in which this is the possibility of generating type error. We will enter the way we handle the above exceptions in except block by printing the user-defined error message.

Let us understand in more detail with the help of an example

Example:

# python program to handle the type error exception


l1 = ["Apple", "Mango", "Banana", "Grapes"]             # declaring a list
indices = [0, 1, 2, "2", 3]
for i in range(len(indices)):
    try:
        print(l1[indices[i]])                                        # case which generates TypeError
    except TypeError:
        print("TypeError: Check list of indices")

The output of the above example of exception handling:

TypeError string indices must be an integer

Related Topics

Division in Python

In this tutorial, we will understand what mathematical operation division is and how is it performed in Python Programming language. We will also focus on the operators being used in...

3 minutes read.

Tensorflow Angular in Python

TensorFlow is an open-source, Python-compatible toolkit for numerical computation that accelerates and simplifies the creation of neural networks and machine learning algorithms. They make the interesting notion that models can be...

6 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

How to Take Input in Python

How To Take Input In Python Python has various in-built functions that help in code redundancy. Let's discuss the usage of some functions- ascii() – it returns a readable representation of objects.format()...

4 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Python History

Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. Python language is known for its features. Some features are given below: SimplisticFree and open...

4 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python sorted() function

Python sorted() function The sorted() function returns a sorted list of the specified iterable object. Syntax sorted(iterable, *, key=None, reverse=False) Parameter iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc. key:...

1 minute read.