[Tutor] The Format Specification Mini-Language of Python 3.1

Richard D. Moores rdmoores at gmail.com
Wed Oct 27 18:29:05 CEST 2010


I finally have learned the bare bones of the Format Specification
Mini-Language of Python 3.1+, and thought I'd share something of what I've
learned with fellow Tutorees who might be interested. I find this
"mini-language" to be a refreshing change from the formatting in use in 2.6,
etc. But when I first saw it in Learning Python, 4th ed., I was put off by
it and never went back until I needed to yesterday. It was the docs
themselves that had the best explanation and examples. So here are those
links:
<
http://docs.python.org/py3k/library/string.html#format-specification-mini-language
>
<http://docs.python.org/py3k/library/string.html#format-examples>

I wanted to have the columns of output from my
dollar2yen_rate_simple_for_python31.py line up correctly, and found, after a
bit of experimentation, how to do it. If you run it (with Python 3.1+ (not
3.0)) <http://tutoree7.pastebin.com/5Z4g60L5>, you'll see that the new
formatting works perfectly -- the minus signs don't produce a jaggedness in
those two columns 3 and 4 any more. Here's a screen shot of some lines of
output: <http://www.rcblue.com/Misc/columns.jpg>

I found that formatting a number as a percentage is easy with the
mini-language. Here's an example I whipped up:

>>> a = 123.345
>>> b = 567
>>> a/b
0.21753968253968253
>>> print('{:.2%}'.format(a/b))
21.75%



In addition, if you are interested in doing some simple web scraping with
3.1, highlighted lines 6, 25, 26 in my code show what worked for me with
what at first was very hard to understand until I found the examples in the
docs for the use of urllib.request: <
http://docs.python.org/py3k/library/urllib.request.html?highlight=urllib#examples>


I've heard that a better way is to use BeautifulSoup (<
http://www.crummy.com/software/BeautifulSoup/>), but figuring that out is a
bit of a ways down my TODO list.

Dick Moores
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101027/0458da3e/attachment-0001.html>


More information about the Tutor mailing list