0

In python, what does the 2nd % signifies?

print "%s" % ( i )
Joan Venge
  • 292,935
  • 205
  • 455
  • 667

5 Answers5

8

As others have said, this is the Python string formatting/interpolation operator. It's basically the equivalent of sprintf in C, for example:

a = "%d bottles of %s on the wall" % (10, "beer")

is equivalent to something like

a = sprintf("%d bottles of %s on the wall", 10, "beer");

in C. Each of these has the result of a being set to "10 bottles of beer on the wall"

Note however that this syntax is deprecated in Python 3.0; its replacement looks something like

a = "{0} bottles of {1} on the wall".format(10, "beer")

This works because any string literal is automatically turned into a str object by Python.

Alan Rowarth
  • 1,960
  • 2
  • 11
  • 10
5

The second % is the string interpolation operator.

Link to documentation.

Brendan
  • 18,163
  • 17
  • 79
  • 106
Ali Afshar
  • 39,783
  • 12
  • 90
  • 108
0

It's a format specifier

Simple usage:

# Prints: 0 1 2 3 4 5 6 7 8 9
for i in range(10):
    print "%d" % i,
Kenan Banks
  • 198,060
  • 33
  • 151
  • 170
0
print "%d%s" % (100, "trillion dollars") # outputs: 100 trillion dollars
Jason Coon
  • 16,505
  • 10
  • 39
  • 50
0

If you were to translate the code to English, it says: take the string i and format it in to the predicate string.

Another example:

name = "world"
print "hello, %s" % (name)

More information about format specifiers.

Nick Stinemates
  • 38,929
  • 21
  • 58
  • 60