Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
typeerror

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

Educative Answers Team

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")
Getting the error
x = "11"
# This tells the compiler that % is used as the modulus operator
if(int(x) % 2):
  print("x is odd")
Resolution using int()

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))
Getting the error
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))
Resolution by matching the number of specifiers and values

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)
Getting the error
fav_food = "pizza"
fav_show = "Friends"
print ("I like to eat %s while watching %s." % (fav_food, fav_show))
Resolution using % and tuple
fav_food = "pizza"
fav_show = "Friends"
print ("I like to eat {0} while watching {1}.".format(fav_food, fav_show))
Resolution using .format()

RELATED TAGS

python
typeerror
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring