Python:具有不同字符串长度的均匀空间输出数据

时间:2015-10-24 21:45:46

标签: python python-3.x

我试图让我的输出数据看起来像这样:

-------------------------------------------------------
            Grade Report for Programs 
-------------------------------------------------------
Jacobson, Mark      19.0 <--- 20,17,20
Snurd, Mortimur     16.5 <--- 20,19,18,17,16,15,14,13
Luxemburg, Rosa     15.0 <--- 18,15,20,10,12
Atanasoff, John     20.0 <--- 20,20,20,20,20,20,20
Hopper, Grace       20.0 <--- 20,20,20,20,20,20
-------------------------------------------------------

但我不知道如何处理不同的名字长度。我的输出目前看起来像这样。

            Grade Report for Programs 
-------------------------------------------------------
Jacobson, Mark   19.0 <--- 20,17,20
Snurd, Mortimur   16.5 <--- 20,19,18,17,16,15,14,13
Luxemburg, Rosa   15.0 <--- 18,15,20,10,12
Atanasoff, John   20.0 <--- 20,20,20,20,20,20,20
Hopper, Grace   20.0 <--- 20,20,20,20,20,20
-------------------------------------------------------

我编写的程序是获取成绩分数的输入文件并收集数据并整齐地打印出平均值。

输入文件如下所示:

Mark Jacobson,20,17,20
Mortimur Snurd,20,19,18,17,16,15,14,13
Rosa Luxemburg,18,15,20,10,12
John Atanasoff,20,20,20,20,20,20,20
Grace Hopper,20,20,20,20,20,20

这是我的代码,它收集姓名和分数,并打印出姓氏,名字,平均分数,然后是平均分数的实际分数。

file = input("Enter filename: ")

grade_file = open(file, 'r')

print()

print('---------------------------------------------------------')
print('\t\tGrade Report for Programs')
print('---------------------------------------------------------')

for text in grade_file:
    end_of_name = text.find(',')
    name_seperated = text.find(' ')

    first_name = text[0:name_seperated]
    last_name = text[name_seperated+1:end_of_name]

    name_last_first = last_name + "," + " " + first_name

    grades = text[end_of_name+1:]

    start = 0
    index = 0
    sum_n = 0
    average= 0
    score = 0
    count = 0

    while index < len(grades):
        if grades[index] == ',':
            score = int(grades[start:index])
            count += 1
            sum_n = score + sum_n
            start = index + 1
        index += 1

    count += 1       

    score = int(grades[start:index])
    sum_n = score + sum_n
    average = sum_n / count



    print(name_last_first, " ", average, "<---", grades)


print('---------------------------------------------------------')


grade_file.close()

我只需要弄清楚如何使用偶数空格,这样它就像第一个输出一样产生偶数行和列。非常感谢帮助!谢谢!

4 个答案:

答案 0 :(得分:6)

我发现使用Python的内置C风格格式更简单:

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

请注意,负字段宽度表示该字段是左对齐的。

答案 1 :(得分:4)

对字段宽度说明符使用字符串格式:

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

这会将str.format() methodFormat String Syntax一起用于将值插入模板。

第一个插槽将字符串格式化为20个字符宽的字段,第二个插槽将浮点数字格式化为4个字符宽的字段,使用小数点后的1个数字(小数点本身加1,加点前2个数字)

如果我是你,我也会查看csv module来读取你的数据,而不是使用字符串操作。您将获得每列具有单独值的列表对象:

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('---------------------------------------------------------')

答案 2 :(得分:0)

我觉得最简单的答案就是使用一些基本的字符串算法。

例如,假设想要在左对齐之前对齐一个变量20个空格,在你的情况下是&#34;平均值&#34;变量,你可以简单地做到这一点

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

它只是有点长,但在我看来代码更容易理解。

(注意:此方法仅适用于单声道间隔字体!但大多数Python输出默认为MS字体:-))

答案 3 :(得分:0)

您可以使用以下代码:

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]))

最后一行用于以有组织的方式显示它,您的代码只是缺少它。