Table of Contents
Overview
Problem Formulation: How to fix Type Error-Not all arguments converted during string formatting
in Python?
Example: Consider the following program that checks if a number is even or odd.
1 2 3 4 5 6 7 |
x = input('Enter A Number: ') if x % 2 == 0: print(x, "is an Even Number!") else: print(x, "is a Odd Number!") |
Output:
Enter A Number: 11
Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 2, in <module>
if x % 2 == 0:
TypeError: not all arguments converted during string formatting
Confused! 🤔 No worries, in this article, you will understand the reasons behind such errors with the help of numerous examples and scenarios. Most importantly, you will learn how to deal with it. So without further delay, let us begin our discussion.
❑ What is TypeError in Python?
Python raises a Type Error Exception when you try to perform an operation on two different/unrelated types of operands or objects. Thus, you will encounter a TypeError
when you try to call a function or use an operator on something of the incorrect type.
Example:
1 2 3 |
print('Java'+2+'Blog') |
Output:
File “main.py”, line 1, in
print(‘Java’+2+’Blog’)
TypeError: can only concatenate str (not “int”) to str
In the above example, the plus operator (+
) was expected between two numeric parameters or two strings, i.e., objects of the same type. However, we tried to concatenate a string and a numeric value which lead to the occurrence of TypeError: can only concatenate str (not "int") to str
.
Solution: To avoid the above TypeError
, you must ensure that you concatenate objects of the same type (str
in this case.)
1 2 3 4 |
print('Java'+'2'+'Blog') # Output: Java2Blog |
This brings us to our next question 👇
❑ How to Fix Type Error: not all arguments converted during string formatting in Python?
Let’s have a look at few examples/scenarios to understand how we can resolve Type Error: not all arguments converted during string formatting
in our code.
💡 Scenario 1: No Format Specifier With The String Interpolation Operator
➣ The most common ways of formatting strings in Python are:
- The old style of string formatting i.e. using the
%
operator. - By using
{}
operator with the.format ()
function.
⚠️ Note: You should not use both together. When you mix both the styles of string formatting, Python throws Type Error: not all arguments converted during string formatting
.
Example:
1 2 3 4 5 6 |
f_name = input("Enter your first name: ") l_name = input("Enter your last name: ") print("Your Name: {} {}" % f_name, l_name) |
Output:
Enter your last name: Sayon
Traceback (most recent call last):
File “main.py”, line 3, in <module>
print(“Your Name: {} {}” % f_name, l_name)
TypeError: not all arguments converted during string formatting
Explanation: In the above example, we tried to mix both the styles of string formatting which lead to the occurrence of TypeError
.
Solution: To overcome this problem, you must stick to a single style of string formatting.
Hence, use one of the following types as show in the solutions below:
☞ Method 1: Using format() function
1 2 3 4 5 6 7 |
f_name = input("Enter your first name: ") l_name = input("Enter your last name: ") print("Your Name: {} {}".format(f_name, l_name)) # new way |
Output:
Enter your last name: Sayon
Your Name: Shubham Sayon
☞ Method 2: Using % Operator (String Interpolation Operator)
1 2 3 4 5 |
f_name = input("Enter your first name: ") l_name = input("Enter your last name: ") print("Your Name: %s %s"%(f_name,l_name)) # old way |
Output:
Enter your last name: Sayon
Your Name: Shubham Sayon
💡 Scenario 2: Incorrect Usage of % Operator
In Python %
operator can be used in two ways:
- Used to find the modulus
- When used with numbers / numeric calculations.
- Used for string formatting
- When used with a string within the
print
statement.
- When used with a string within the
Now, if you confuse between the two usages and try to find the modulus of a string input/value, you will encounter a TypeError
.
Example: Program to check leap year.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
year = input('Enter the year: ') if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) |
Output:
Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 2, in <module>
if (year % 4) == 0:
TypeError: not all arguments converted during string formatting
Explanation: We tried to use the % operator on a string input in the second line of our code. This lead to the occurrence of the TypeError
.
Solution: Ensure that the user input is an integer value by using the int()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
year = int(input('Enter the year: ')) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) |
Output:
2008 is a leap year
💡 Scenario 3: Missing Format Specifiers While Using % for String Formatting
When the number of format specifiers present is less than than number of values passed, it leads to the occurrence of TypeError: not all arguments converted during string formatting
.
Example:
1 2 3 |
print("%d+%d=25"%(10,15,25)) |
Output:
File “D:/PycharmProjects/PythonErrors/rough.py”, line 1, in <module>
print(“%d+%d=25″%(6,4,15))
TypeError: not all arguments converted during string formatting
Solution: The obvious solution to this problem is to use an equal number of values and format specifiers. Another approach to avoid this problem is to use the .format()
method for string formatting.
.format ()
ensures that only the exact number of values as the number of {} specifiers in the string expression is passed, and the extra values are ignored.
1 2 3 |
print("{}+{}=25".format(10,15,25)) |
Output:
Conclusion
So, in this article, you learned about TypeError
: not all arguments converted during string formatting
. And now, you are all set to solve this irritating bug like a Pro!
Read more here: [Solved] TypeError: Can’t Multiply Sequence by non-int of Type ‘float’ In Python?
Please stay tuned and subscribe for more interesting articles.