Online Tutorials & Training Materials | STechies.com
Register Login

TypeError: not all arguments converted during string formatting

14 Jan 2020 12:19 pm || 0

What is the “TypeError: not all arguments converted during string formatting” error?

In Python, a TypeError is encountered when you perform an operation or use a function on an object of the incorrect type. You might encounter these errors when working with integers and strings. Such a common error is TypeError: not all arguments converted during string formatting. This error is caused when there is a mismatch in data types and strings are not properly formatted.

The solution to this error is to use proper string formatting functions such as int() or str() to obtain the desired data type.

Let us take a look at an example where this error is raised:

# Enter number from user
num = (input("Enter a Number: "))

# Divided Number with integer 5  
reminder = num % 5
print(num,' Divide by 5 Reminder is : ', reminder)

Output:

 reminder = num % 5
TypeError: not all arguments converted during string formatting

In this program, the TypeError is raised as the num variable accepts input in the form of a string from the user. So, the modulus operation (%) cannot be performed on it and it cannot be divided by an integer 2.

TypeError: not all arguments converted during string formatting

Here is a way to fix it:

# Enter number from user
num = (input("Enter a Number: "))
# Divided Number with integer number 5
reminder = int(num) % 5
print(num,' Divide by 5 Reminder is : ', reminder)

Here, the function int() is used to convert the string in the variable num into an integer. It is then easily divided by 2 using the modulus operation, to determine whether it is an odd number or not.

Take a look at another example:

# Input Name and Age from user
name = input("Enter name : ")
age = input("Enter Age  : ")

# Print Name and Age of user
print("'{0}'Age is '{1}'"% name, age)

Output

    print("'{0}'Age is '{1}'"% name, age)
TypeError: not all arguments converted during string formatting

You can resolve this error by using the modern methods of formatting provided by Python – the format() method. Change the code like this:

# Input Name and Age from user
name = input("Enter name : ")
age = input("Enter Age  : ")

# Print Name and Age of user
print("'{0}'Age is '{1}'".format(name, age))

This fixes the error as the new formatting method uses {} along with the format() method.