Elementary string-formatting
Matt Nordhoff
mnordhoff at mattnordhoff.com
Sun Jan 13 05:26:49 EST 2008
Odysseus wrote:
> Hello, group: I've just begun some introductory tutorials in Python.
> Taking off from the "word play" exercise at
>
> <http://www.greenteapress.com/thinkpython/html/book010.html#toc96>
>
> I've written a mini-program to tabulate the number of characters in each
> word in a file. Once the data have been collected in a list, the output
> is produced by a while loop that steps through it by incrementing an
> index "i", saying
>
> print '%2u %6u %4.2f' % \
> (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0])
This isn't very important, but instead of keeping track of the index
yourself, you can use enumerate():
>>> mylist = ['a', 'b', 'c']
>>> for i, item in enumerate(mylist):
... print i, item
...
0 a
1 b
2 c
>>>
Err, it doesn't look like you can make it start at 1 though.
<snip>
--
More information about the Python-list
mailing list