Emmy Ebanks
Emmy Ebanks

Reputation: 21

%d within print statement python

I encountered this in a function of a program and I don't understand how the %d can work inside a closed quote print statement.

print "%d squared is %d." % (n, squared)

The output when the argument of 10 (which is n) is passed is: 10 squared is 100

Upvotes: 2

Views: 8372

Answers (1)

user3636636
user3636636

Reputation: 2499

The "%" operator is used to format a set of variables enclosed in a tuple (a fixed size list), together with a format string.

print ("%d squared is %d" % (10, 10*10))

The % operators in the string are replaced in order by the elements in the tuple.

%d is used for integers, where as %s is used for strings

Eg.

>>>name = "John"
>>>age = 23
>>>print "%s is %d years old." % (name, age)
John is 23 years old.

Upvotes: 1

Related Questions