Search code examples
pythonpython-3.xtextalignmenttext-alignment

How can I align this text file?


I appended values to a text file and I want to align it with the category on top, I have about 500 names and 10 categories so I cant do it line by line. I posted a small example on the bottom. I also want the first category to only have 23 characters max. This is what I did so far:

   fp = open(filename, "w")
   fp.write("Name                 Team Pos Games G A Pts PIM SOG Hits BS \n===========================================================\n")
   for items in stats:
          fp.write(str(items[0][:20])+ "  " + str(items[1]))
          fp.write('\n')
   fp.close()

This is the part I'm guessing I need to fix:

   fp.write(str(items[0][:23])+ "  " + str(items[1]))

Heres a snipit of the output I get:

Name                 Team
=========================
A.J. Greer  COL
Aaron Ekblad  FLA
Adam Clendening  CLS
Adam Cracknell  FA
Adam Erne  DET
Adam Gaudette  VAN
Adam Henrique  ANH
Adam Johnson  PIT
Adam Larsson  EDM
Adam Lowry  WPG
Adam McQuaid  FA
Adam Pelech  NYI
Adrian Kempe  LA
Alan Quine  CGY
Alec Martinez  LA
Aleksander Barkov  FLA

Solution

  • fp.write("%-21s%-4s" % (items[0],items[1]))
    

    Tested with parse and reprint.

    import re
    
    TESTLINES = """A.J. Greer  COL
    Aaron Ekblad  FLA
    Adam Clendening  CLS
    Adam Cracknell  FA
    Adam Erne  DET
    Adam Gaudette  VAN
    Adam Henrique  ANH
    Adam Johnson  PIT
    Adam Larsson  EDM
    Adam Lowry  WPG
    Adam McQuaid  FA
    Adam Pelech  NYI
    Adrian Kempe  LA
    Alan Quine  CGY
    Alec Martinez  LA
    Aleksander Barkov  FLA"""
    
    print("Name                 Team")
    print("=========================")
    for line in TESTLINES.split("\n"):
       (name, team) = re.findall(r"^(.*?)\s+(\S+)$", line)[0]
       print("%-21s%-4s" % (name,team))