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
1 | print("{0} and {1} are even numbers"%(2,10)) |
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.
1 | print("%d and %d are even numbers"%(2,10)) |
Correct Syntax 2: Use {}
with .format
method.
1 | print("{0} and {1} are odd numbers".format(3,11)) |
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
1 | print("%d and %d are even numbers"%(2,4,6)) |
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.
1 | print("%d, %d, and %d are even numbers"%(2,4,6)) |
Correct Syntax 2: Use {}
with .format
method.
1 | print("{0} and {1} are odd numbers".format(3,11,15)) |
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.