-2

I want to pass two parameters to my string, using % s.

I tried this, but it did not work :

title = "im %s with %s"
title % "programming" % "python"

it gives this error :

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

Do you have an idea? thanks

Levon
  • 138,105
  • 33
  • 200
  • 191
ilias
  • 182
  • 1
  • 3
  • 13
  • 2
    This is something you answer by looking in the same place that you found out that there is a `%` operation in the first place. – Karl Knechtel May 19 '12 at 19:03

3 Answers3

8

The correct syntax is:

title = "im %s with %s"
title % ("programming", "python")

The % operator takes two operands:

  1. the format string goes on the left-hand side;
  2. the tuple containing all the arguments goes on the right-hand side (if there's only one parameter, it can be a scalar).
NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

The problem is probably best understood by breaking down how these formatting directives work. The basic idea is that each % in a string means an argument needs to be subsequently supplied to the string.

For instance, this would work:

title = "i'm %s with %s" % ('programming', 'python')

and yield

"i'm programming with python"

The 's' in %s means that this is a place holder for a string. A 'd' would be for integers, 'f' for floats etc. There are also additional parameters you can specify. See these docs.

If you don't supply enough items for each place holder, it will result in the not enough arguments for format string message.

Your specific example first creates a string constant that has two formatting directives in it. Then when you use it, you'll have to supply two items for it.

In other words,

title = "i'm %s with %s"
title % ('programming', 'python')

becomes

"i'm %s with %s" % ('programming', 'python')
Levon
  • 138,105
  • 33
  • 200
  • 191
1

Not really an answer but:

You may also use something like:

title = "im %(doing)s with %(with)s"
title % {'doing': 'programming', 'with': 'python'}

or:

title = "im %(doing)s with %(with)s" % {'doing': 'programming', 'with': 'python'}

Where instead of %s you use %(your dictionary key)s and instead of a tuple you pass a dict after the modulo operator.

Check String formatting operations

PabloRosales
  • 348
  • 3
  • 11