I am reading thru DiveIntoPython docs and it gives some examples
Example 3.23. Formatting Numbers
>>> print "Today's stock price: %f" % 50.4625
50.462500

The 1st % designates Formatting, what does the 2nd % do?
Thanks!

Recommended Answers

All 4 Replies

that just makes sure the program knows where to look to find the variables. So if more than one thing was in the formatted string you would use a tuple.

That is:
s = "---> Increased"
print "Today's stock price: %f %s" % (50.4625, s)

That is:
s = "---> Increased"
print "Today's stock price: %f %s" % (50.4625, s)

You got it ;)

that just makes sure the program knows where to look to find the variables. So if more than one thing was in the formatted string you would use a tuple.

It's required to enclose the variable in parentheses in this case:

>>> a = 5
>>> b = 10
>>> print "%0.4f" % a*b
5.00005.00005.00005.00005.00005.00005.00005.00005.00005.0000
>>> print "%0.4f" % b/a
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> print "%0.4f" % (a*b)
50.0000
>>>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.