Formatting the Little Things
Python’s formatting method is my favorite code discovery of the week.
The formatter responds to replacement fields surrounded by curly braces, enveloped in a string. Call the “format” method on the string, specifying which values to place inside those curly braces and ta-da, beauty.
You can even define your own formatting object. Here’s an example to help format one of life’s most difficult questions:
class DeepThought(object):
def __format__(self, format):
if (format == 'answer-to-ultimate-question'):
return "42."
return "What's the question?"
print "{:answer-to-ultimate-question}".format(DeepThought()) <b></b>
42.
In sum,
num = 100.033452
adj = "real"
print "Things just got {0}. And {1:0.0f} times prettier.".format(adj,num) <b></b>
Things just got real. And 100 times prettier.
July 27, 2015