Fix TypeError: Not Enough Arguments for Format String Error in Python

Fix TypeError: Not Enough Arguments for Format String Error in Python

In Python, we can format strings to get the final result in our desired style and format.

String formatting also involves using placeholder values with the % sign. This method is a very common technique to provide missing values in Python with temporary values.

However, if one is not careful, it may lead to the not enough arguments for format string error, a TypeError. We will discuss this error and its solutions in this tutorial.

See the following code.

a = 2
b = 4
c = 6
s = "First %s Second %s Third %s" %a,b,c
print(s)

Output:

TypeError: not enough arguments for format string

We get this error because we provide only one % sign in the string to give the values, and there are three values. The above code only considers the first value (a). We need to pass them in a tuple to solve this.

For example:

a = 2
b = 4
c = 6
s = "First %s Second %s Third %s" %(a,b,c)
print(s)

Output:

First 2 Second 4 Third 6

Another way to overcome this error is by using the format() function. The % method is outdated for formatting strings.

We can specify the values in the format() function and mention the missing values using curly braces {}.

See the code below.

a = 2
b = 4
c = 6
s = "First {0} Second {1} Third {2}".format(a, b, c)
print(s)

Output:

First 2 Second 4 Third 6

In Python 3.x and above, we can use the fstrings to provide placeholder strings. This method is a newer and more efficient way to format strings.

We can provide the values within curly braces as done in the previous example.

See the following example.

a = 2
b = 4
c = 6
s = f"First {a} Second {b} Third {c}"
print(s)

Output:

First 2 Second 4 Third 6
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python