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

ID : 28

viewed : 278

Tags : PythonPython String

vote vote

98

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 

  • Related HOW TO?