Python: Evenly space output data with varying string lengths

前端 未结 4 503
走了就别回头了
走了就别回头了 2021-01-04 14:30

I am trying to get my output data to look like this:

-------------------------------------------------------
            Grade Report for Programs 
---------         


        
相关标签:
4条回答
  • 2021-01-04 14:48

    The answer I find easiest is just using some basic string arithmetic.

    For example, say for want the aligned a variable 20 spaces ahead of left-alignment, in your case the "average" variable, you could simply do this

    print(name_last_first + (' ' * (20-len(name_last_first))) + average
           + "<----" + grades)
    

    It's just a bit lengthier, but the code is easier to interpret in my opinion.

    (Note: this method only works with mono spaced fonts! But most Python output is defaulted to a MS font :-) )

    0 讨论(0)
  • 2021-01-04 15:04

    Use string formatting with field width specifiers:

    print('{:20s} {:4.1f} <--- {}'.format(name_last_first, average, grades))
    

    This uses the str.format() method with the Format String Syntax to slot values into a template.

    The first slot formats strings into a field 20 characters wide, the second slots floating point numbers into a field 4 characters wide, using 1 digit after the decimal point (leaving 1 for the decimal point itself plus 2 digits before the point).

    If I were you, I'd also look at the csv module to read your data, rather than use string manipulations. You'll get list objects with separate values for each column:

    import csv
    
    print('---------------------------------------------------------')
    print('\t\tGrade Report for Programs')
    print('---------------------------------------------------------')
    
    with open(file, 'r', newline='') as grade_file:
        reader = csv.reader(grade_file)
        for row in reader:
            name = row[0]
            name = ' '.join(map(str.strip, reversed(name.split(',')))
            grades = [int(g) for g in row[1:])
            average = sum(grades) / len(grades)            
            print('{:20s} {:4.1f} <--- {}'.format(name, average, ','.join(grades)))
    
    print('---------------------------------------------------------')
    
    0 讨论(0)
  • You can use this code :

    handle = open('grade.txt')
    name= list()
    avg = list()
    scores = list()
    
    for line in handle:
        line = line.strip()
        spos = line.find(',')
        scores.append(line[spos+1:])   
        words = line.split(',')
        words = words
        name.append(words[0])
        add = 0
    
        for i in range(1,len(words)):
            add = add+int(words[i])
    
        average = add/(len(words)-1)
        avg.append(average)
    
    for i in range(len(avg)):
        tname = name[i].split()
        fname = tname[0]
        sname = tname[1]
        order = sname+', '+fname
        print("%-20s %-3.1f <---  %-30s " %(order,float(avg[i]),scores[i]))
    

    The final line is for displaying it in an organized manner, you're code was lacking it only.

    0 讨论(0)
  • 2021-01-04 15:05

    I find it simpler to use Python's builtin C-style formatting:

    >>> print("%-30s %4.1f" % ("Jacobson, Mark", 19.0))
    Jacobson, Mark                 19.0
    >>> 
    

    Note that a negative field width indicates that the field is to be left-justified.

    0 讨论(0)
提交回复
热议问题