Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

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



ADVERTISEMENT
ADVERTISEMENT