0

In python, what does the 2nd % signifies?

print "%s" % ( i )

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

The second % is the string interpolation operator.

Link to documentation.

Comments

0
print "%d%s" % (100, "trillion dollars") # outputs: 100 trillion dollars

1 Comment

Actually, it outputs "100trillion dollars" — you're missing a space. :-)
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.

Comments

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,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.