align on char

John Hunter jdhunter at nitace.bsd.uchicago.edu
Mon Jun 21 13:07:10 EDT 2004


>>>>> "Peter" == Peter Otten <__peter__ at web.de> writes:

    Peter> I think you are cheating. You don't know maxa until the
    Peter> loop has finished.

Thanks to all who replied; I took a composite of all the suggestions
to produce

def alignon(lines, c):
    """
    lines is a list of strings, all of which contain c.  Return a new
    list of strings aligned on c

    If line does not contain alignment char c, a ValueError is raised
    """
    width = 0
    ab = []
    for line in lines:
        tup= line.split(':',1)
        if len(tup) !=2:
            raise ValueError('Line "%s" does not contain char "%c"' %(line, c))
                             
	width = max(width, len(tup[0]))
        ab.append(tup)
    
    return ["%-*s:%s" % (width, a, b) for a, b in ab]


lines = (
  'user1 : John Hunter',
  'another user : Bill Bragg',
  'yet more : Hi There',

)

for line in alignon(lines, ':'):
    print line





More information about the Python-list mailing list