Trusted answers to developer questions

Resolving "typeerror: not all arguments converted ... in Python"

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

In Python, “typeerror: not all arguments converted during string formatting” primarily occurs when:

  1. There is no format specifier.
  2. The format specifiers and the number of values are different.
  3. Two format specifiers are mixed.

Code

1. No format specifier with the string interpolation operator

# Since `x` is a string, the `%` operator is treated as a string
# interpolation operator. The error occurs because no format specifier
# is provided.
x = "11"
if(x % 2):
print("x is odd")
x = "11"
# This tells the compiler that % is used as the modulus operator
if(int(x) % 2):
print("x is odd")

2. Unequal format specifiers and values

fav_food = "pizza"
fav_show = "Friends"
fav_day = "Saturday"
fav_month = "June"
print("I like to eat %s while watching %s." % (fav_day, fav_food, fav_month, fav_show))
fav_food = "pizza"
fav_show = "Friends"
fav_day = "Saturday"
fav_month = "June"
print("I like to eat %s while watching %s." % (fav_food, fav_show))

3. Two format specifiers are mixed.

fav_food = "pizza"
fav_show = "Friends"
print ("I like to eat '{0}' while watching '{1}'." % fav_food, fav_show)
fav_food = "pizza"
fav_show = "Friends"
print ("I like to eat %s while watching %s." % (fav_food, fav_show))
fav_food = "pizza"
fav_show = "Friends"
print ("I like to eat {0} while watching {1}.".format(fav_food, fav_show))

RELATED TAGS

python
typeerror
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?