TypeError: not all arguments converted during string formatting is an error in Python that often occurs in the following cases:
- When two string format specifiers are mixed, and
- When the number of format specifiers is less than the number of values passed.
Let’s see an example of each case along with the solution to prevent the errors.
Case 1: Two String Format Specifiers are Mixed
print("{0} and {1} are even numbers"%(2,10))
TypeError: not all arguments converted during string formatting
In this case, the error occurred because of ambiguous string formatting.
In Python, the following are the correct ways to format string using specifiers.
Correct Syntax 1: Use only %
for formatting.
print("%d and %d are even numbers"%(2,10))
2 and 10 are even numbers
Correct Syntax 2: Use {}
with .format
method.
print("{0} and {1} are odd numbers".format(3,11))
3 and 11 are odd numbers
Mixing the two formatting options often cause the TypeError in Python.
Case 2: Number of Format Specifiers is Less than the Number of Values Passed
print("%d and %d are even numbers"%(2,4,6))
TypeError: not all arguments converted during string formatting
In this case, the print statement has two %
specifiers but three values are passed to it.
To resolve this error either use the {}
with .format
method for formatting string or check the number of specifiers corresponding to the values passed to the string expression.
Correct Syntax 1: Specify correct number of format specifiers.
print("%d, %d, and %d are even numbers"%(2,4,6))
2, 4, and 6 are even numbers
Correct Syntax 2: Use {}
with .format
method.
print("{0} and {1} are odd numbers".format(3,11,15))
3 and 11 are odd numbers
Although more values are passed to the string expression, no error was raised. It is because the .format()
passes only the exact number of values as the number of {}
specifiers in the string expression and rest are ignored.
In this post, we got to know why ‘TypeError: Not all arguments converted during string formatting’ error occurs and how fix this error in Python.