align on char

Batista, Facundo FBatista at uniFON.com.ar
Thu Jun 17 21:07:43 CEST 2004


[John Hunter]

#- Suppose you have a sequence of strings, all known to have at 
#- least one
#- occurance of char
#- 
#- lines = (
#-   'user1 : John Hunter',
#-   'another user : Bill Bragg',
#-   'yet on more : Hi There', 
#- )
#- 
#- what is the best / easiest / most elegant way of producing this?
#- 
#- aligned = (
#-   'user1        : John Hunter',
#-   'another user : Bill Bragg',
#-   'yet on more  : Hi There', 
#- )


My way:

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

>>> lines
('user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi
There')
>>> aligned = []
>>> maxa = 0
>>> for line in lines:
	(a, b) = line.split(':')
	maxa = max(maxa, len(a))
	aligned.append(':'.join((a.ljust(maxa),b)))

>>> aligned
['user1        : John Hunter', 'another user : Bill Bragg', 'yet on more  :
Hi There']
>>> print '\n'.join(aligned)
user1        : John Hunter
another user : Bill Bragg
yet on more  : Hi There


.	Facundo




More information about the Python-list mailing list