×

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

Falcon Python

Introduction of Python Python is the fastest and the smartest programming language and it is an object oriented language. Python has libraries that can be importedeasily and perform many operations; to...

3 minutes read.

How to convert integer to float in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

5 minutes read.

How to Define a Function in Python?

What is a Function? In programming, a piece of code that executes a specific task or a group of related operations is known as a function. What does Python Functions Do? If you...

6 minutes read.

Python slice()

Python slice() class The slice() class return a slice object representing the set of indices specified by range(start, stop, step).  Syntax class slice(stop)          or class slice(start, stop[, step]) Parameter Start: This parameter represents an integer number specifying at...

1 minute read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

Python Multiprocessing Processor

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

4 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Python String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

Python Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text] Python Set Methods A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets. Methods ...

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.

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.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.