×

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

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Python tuple() function

Python tuple() function The tuple() function in Python creates a tuple object. Syntax tuple([iterable]) Parameter Iterable: This parameter represents a sequence, collection or an iterator object. Return This function returns a tuple object. Example 1 # Python Program explaining #...

1 minute read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Python program to display ASCII value of the character

Python program to display ASCII value of the character The full form of ASCII is American Standard Code for Information Interchange. This example explains a program in Python to find the...

1 minute read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it...

4 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

Python Unit Test Cheat String

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to open a file in python

Opening a File in Python Python is a user-friendly programming language that makes almost every concept easy. It provides many inbuilt functions in its libraries to work with files. Using these...

6 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

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

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.