[Tutor] A style question

Raymond Hettinger python@rcn.com
Thu, 18 Apr 2002 13:09:54 -0400


> > Is there a way to reduce the number of lines needed
>
> > output.write("Number of lines: %s\n" % str(linecount))
> >     output.write("Total word count: %s\n" % str(wordcount))
> >     output.write("Total character count: %s\n\n"% str(charcount))

The lines can be combined and the str() conversion isn't necessary if you
use %d instead of %s:

output.write( 'Number of lines: %d\nTotal word count: %d\n Total character
count: %d\n\n' % (linecount, wordcount, charcount) )


> >     for word in keyList:
>           strOut = "word: %15s,\toccurences: %d\n" %
(word,occurences[word])
>           output.write(strOut)

Looping over .items() lets you get the word and the count in one lookup and
the tuple can be used to feed the formatting operator:

for wordcountpair in occurences.items():
     output.write( 'word: %15s,\t occurences: %d\n' % wordcountpair )


Using a list comprehension lets you do the output with writelines:

output.writelines(['word: %15s,\t occurences: %d' % pair for pair in
occurences.items()]

>
> Notes:
> %15s -> a string occupying 15 spaces(makes it all line up)
> \t -> tab
> %d prints a number, no need for str()
>
> Any better?

Removing the 15s and \t makes it longer and, in my book, not as clear.


BTW,  run a spell-check on 'occurences' ;)


Raymond Hettinger