tags:

views:

256

answers:

6

In python, what does the 2nd % signifies?

print "%s" % ( i )
A: 

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,
Triptych
nosklo
Funny, I often do that same typo in real code.
Ali A
+5  A: 

The second % is the string interpolation operator.

Link to documentation.

Ali A
+1: Quote the documentation.
S.Lott
A: 
print "%d%s" % (100, "trillion dollars") # outputs: 100 trillion dollars
jcoon
Actually, it outputs "100trillion dollars" — you're missing a space. :-)
Ben Blank
A: 

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
+7  A: 

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
A: 

See also this related question.

Cal Jacobson