user3167683
user3167683

Reputation: 131

Python string formatting with "write"

I have some code like this:

#w = open("blabla.py", "w") is already called
w.write("Button(root, text = %s,command=%s).grid(row=%s,column=%s)\n" % textvalue,buttoncommand,str(rowvalue),str(columnvalue))

However, if I run this, I get the following error:

TypeError: not enough arguments for format string

What is wrong?

Upvotes: 0

Views: 89

Answers (3)

MAcabot
MAcabot

Reputation: 544

If you pass multiple arguments to a format string you need to put them in brackets:

w.write("Button(root, text = %s,command=%s).grid(row=%s,column=%s)\n" % (textvalue,buttoncommand,str(rowvalue),str(columnvalue)))
                                                                        ^                                                      ^

You also might want to take a look at the new format syntax: https://docs.python.org/2/library/string.html#format-examples

Upvotes: 0

Martin Rajnoha
Martin Rajnoha

Reputation: 11

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

... % (textvalue,buttoncommand,str(rowvalue),str(columnvalue))

but the % syntax for formatting strings is becoming outdated. Try this:

"'{0}', '{1}', '{2}', '{3}', '{4}'".format(textvalue,buttoncommand,str(rowvalue),str(columnvalue))

Upvotes: 0

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14975

Enclose vars into a tuple:

w.write("Button(root, text = %s,command=%s).grid(row=%s,column=%s)\n" % (textvalue,buttoncommand,str(rowvalue),str(columnvalue)))

Or use a better format version:

w.write("Button(root, text = {0},"
      "command={1}).grid(row={2},"
      "column={3})\n".format(textvalue,
                             buttoncommand,
                             str(rowvalue),
                             str(columnvalue)))

Upvotes: 4

Related Questions