0

In python, what does the 2nd % signifies?

print "%s" % ( i )
Joan Venge
  • 315,713
  • 212
  • 479
  • 689

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
  • 2,250
  • 2
  • 14
  • 10
5

The second % is the string interpolation operator.

Link to documentation.

Brendan
  • 18,771
  • 17
  • 83
  • 114
Ali Afshar
  • 40,967
  • 12
  • 95
  • 109
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
  • 207,056
  • 34
  • 155
  • 173
0
print "%d%s" % (100, "trillion dollars") # outputs: 100 trillion dollars
Jason Coon
  • 17,601
  • 10
  • 42
  • 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
  • 41,511
  • 21
  • 59
  • 60