2

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

6
  • 1
    See Format Specifiers(docs.python.org/2/library/stdtypes.html#string-formatting) Commented Jul 3, 2015 at 6:08
  • That's some very basic Python, look it up in the manual or the tutorial you use. Commented Jul 3, 2015 at 6:08
  • What is the issue you're having? n and squared are both number variables, which replace the %d in the string passed to print. (That's what the % in ... d." % (n, ... is used for). Commented Jul 3, 2015 at 6:08
  • I'm voting to close this question as off-topic because it can be answered with a simple google search. Commented Jul 3, 2015 at 6:09
  • The % operator is string formating - it has nothing to do with the print statement. Commented Jul 3, 2015 at 6:16

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I am a programming newbie. I did a google search btw. I thought it needed to be enclosed in () to do the replacing action but I guess it doesn't. You can delete this question if you want.. Thanks again for your explantion. Cheers

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.