Skip to content
Home » TypeError: not enough arguments for format string Python

TypeError: not enough arguments for format string Python

To solve Python TypeError: not enough arguments for format string error follow below methods.

ERROR LOG

TypeError: not enough arguments for format string

Python strings must be formatted correctly, with the appropriate number of arguments. When the number of parameters specified is less than the number of values to be formatted into a string, an error message such as “TypeError: not enough arguments for format string” appears.

How to solve Python TypeError: not enough arguments for format string ?

This issue frequently occurs when you fail to enclose the arguments in a percent string format in parentheses. To add values to a string, this syntax use the percent operator.

Example:

heros = ['Thor','Spidy','hulk']
value = "%s, %s and %s are the well know heros." % heros[0], heros[1], heros[2]
print(value)

Output:

TypeError  Traceback (most recent call last)
<ipython-input-1-9f29f8505374> in <module>()
      1 heros = ['Thor','Spidy','hulk']
----> 2 value = "%s, %s and %s are the well know heros." % heros[0], heros[1], heros[2]
      3 print(value)
TypeError: not enough arguments for format string

Follow the below steps to resolve.

Method 1: Fix String Formatting Syntax

The values you want to add to a string must be wrapped between parentheses when using the percent operator.

In the above example, we specify the values to include within our string as a list of comma-separated values. This list is not enclosed in parenthesis. We correct our problem by enclosing the data after the percent sign in parenthesis:

code:

heros = ['Thor','Spidy','hulk']
value = "%s, %s and %s are the well know heros." % (heros[0], heros[1], heros[2])
print(value)

Output:

Thor, Spidy and hulk are the well know heros.

Method 2 : Using .format()

The % syntax is quickly becoming outdated. Other techniques of formatting strings, such as the .format() method, are more commonly used in modern Python programming.

Instead of the percent syntax, we may utilize the.format() syntax to fix our problem:

heros = ['Thor','Spidy','hulk']
value = "{}, {} and {} are the well know heros.".format(heros[0], heros[1], heros[2])
print(value)

Output:

Thor, Spidy and hulk are the well know heros.

Hope the above solution works.

Also read :