Python: Evenly space output data with varying string lengths

前端 未结 4 505
走了就别回头了
走了就别回头了 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 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('---------------------------------------------------------')
    

提交回复
热议问题