Formatting a list of text into columns

前端 未结 8 1037
我在风中等你
我在风中等你 2021-02-07 08:34

I\'m trying to output a list of string values into a 2 column format. The standard way of making a list of strings into \"normal text\" is by using the string.join

8条回答
  •  不思量自难忘°
    2021-02-07 09:28

    I think many of these solutions are conflating two separate things into one.

    You want to:

    1. be able to force a string to be a certain width
    2. print a table

    Here's a really simple take on how to do this:

    import sys
    
    skills_defs = ["ACM:Aircraft Mechanic", "BC:Body Combat", "BIO:Biology",
    "CBE:Combat Engineer", "CHM:Chemistry", "CMP:Computers",
    "CRM:Combat Rifeman", "CVE:Civil Engineer", "DIS:Disguise",
    "ELC:Electronics","EQ:Equestrian", "FO:Forward Observer",
    "FOR:Forage", "FRG:Forgery", "FRM:Farming", "FSH:Fishing",
    "GEO:Geology", "GS:Gunsmith", "HW:Heavy Weapons", "IF:Indirect Fire",
    "INS:Instruction", "INT:Interrogation", "JP:Jet Pilot", "LB:Longbow",
    "LAP:Light Aircraft Pilot", "LCG:Large Caliber Gun", "LNG:Language",
    "LP:Lockpick", "MC:Melee Combat", "MCY:Motorcycle", "MEC:Mechanic",
    "MED:Medical", "MET:Meterology", "MNE:Mining Engineer",
    "MTL:Metallurgy", "MTN:Mountaineering", "NWH:Nuclear Warhead",
    "PAR:Parachute", "PST:Pistol", "RCN:Recon", "RWP:Rotary Wing Pilot",
    "SBH:Small Boat Handling","SCD:Scuba Diving", "SCR:Scrounging",
    "SWM:Swimming", "TW:Thrown Weapon", "TVD:Tracked Vehicle Driver",
    "WVD:Wheeled Vehicle Driver"]
    
    # The only thing "colform" does is return a modified version of "txt" that is
    # ensured to be exactly "width" characters long. It truncates or adds spaces
    # on the end as needed.
    def colform(txt, width):
        if len(txt) > width:
            txt = txt[:width]
        elif len(txt) < width:
            txt = txt + (" " * (width - len(txt)))
        return txt
    
    # Now that you have colform you can use it to print out columns any way you wish.
    # Here's one brain-dead way to print in two columns:
    for i in xrange(len(skills_defs)):
        sys.stdout.write(colform(skills_defs[i], 30))
        if i % 2 == 1:
            sys.stdout.write('\n')
    

提交回复
热议问题