The Python Oracle

Python TypeError: not enough arguments for format string

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping

--

Chapters
00:00 Python Typeerror: Not Enough Arguments For Format String
00:26 Answer 1 Score 290
00:51 Accepted Answer Score 191
01:12 Answer 3 Score 28
01:25 Answer 4 Score 0
01:39 Thank you

--

Full question
https://stackoverflow.com/questions/1114...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #format #typeerror

#avk47



ANSWER 1

Score 290


You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'



ACCEPTED ANSWER

Score 191


Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.




ANSWER 3

Score 28


I got the same error when using % as a percent character in my format string. The solution to this is to double up the %%.




ANSWER 4

Score 0


I had the same issue I was using a raw query for a specific reason and this was to add double quotes in TIME_FORMAT function.

User.objects.raw(
            f'SELECT f1,f2,TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(end_time) - TIME_TO_SEC(start_time))),"%%H:%%i") AS log FROM users GROUP BY start_dt')