[Tutor] Need to be taught a trick or two about printing in neat columns

Dick Moores rdm at rcblue.com
Thu Nov 2 11:19:38 CET 2006

At 01:45 AM 11/2/2006, Luke Paireepinart wrote:
>Instead of helping you with your specific problem, I'll give you this
>information and see what you can make of it.
>  >>> print 'a'.ljust(20)+'b'.ljust(20)
>a                   b
>  >>> print 'carrah'.ljust(20)+'foobar'.ljust(20)
>carrah              foobar
>Notice how they're all lined up on the left (if the font in this e-mail
>is fixed-width.  Either way, the number of spaces for both columns is
>the same.)
>ljust's functionality is essentially this:
>def left_justify(astr,width):
>     x = len(astr)
>     while x < width:
>         astr += ' '
>         x += 1

Ah, that's beautiful! Thanks, Luke! (And thanks Python!) Didn't know 
about ljust(). Here's my modified printListOfAllUnitsAndAbbreviations().

def printListOfAllUnitsAndAbbreviations():
         Prints a list of all units and their abbreviations, but not 
their categories.
         lstAll = allUnitsAndTheirAbbreviationsAndCategories()
         for i in range(0, len(lstAll)-1, 3):
                 print lstAll[i][2:].ljust(27) + 
lstAll[i+1][2:].ljust(27) + lstAll[i+2][2:].ljust(27)


More information about the Tutor mailing list