【问题标题】:Formatting a basic table [duplicate]格式化基本表[重复]
【发布时间】:2016-02-06 17:33:05
【问题描述】:
def main():
    infile = open ('correctAnswers.txt','r')
    correct = infile.readlines()
    infile.close
    infile1 = open ('studentAnswers.txt','r')
    student = infile.readlines()
    infile1.close
    index=0
    correctanswer=0
    wronganswer=[]
    while index<len(correct):
        correct[index]=correct[index].rstrip('\n')
        student[index]=student[index].rstrip('\n')
        if correct[index]==student[index]:
            correctanswer=correctanswer+1
            print(index)
            index=index+1
        else:
            wronganswer.append(index)
            print(index)
            index=index+1
    if correctanswer>0:
        print("Congratulations you passed the test.")
    else:
        print("I'm sorry but you did not pass the test")
        print(" ")
        print(" ")
        print("#    Correct   Student ")
        print("-----------------------")
    for item in incorrectindex:
        print(item+1,"     ",correctanswers[item],"    ",studentanswers[item])

main()

这就是我正在执行的整个程序。它读取我在本地拥有的两个文件,检查学生是否有足够的正确答案来通过测试。该程序执行良好,它产生 恭喜你通过了测试。

#    Correct   Student 
-----------------------
3       A      B
7       C      A
11       A      C
13       C      D
17       B      D

问题是看起来很草率,请注意数字从个位数到两位数的变化如何将字母移动一个空格。有没有具体的方法可以做到这一点,因为我知道我将来会遇到这个问题

【问题讨论】:

  • 我没有在您的代码中看到您打印该表格的位置。
  • 呃,我太马虎了
  • 回答了我的问题,那有没有办法删除这个问题?
  • @John,没有必要这样做。你得到了一个有效的答案,即使这个问题最终以重复的形式关闭,它仍然有效。我们不喜欢删除重复项,因为它们为答案提供了多个“路径”,并且不同的人会采用不同的路径。

标签: python format


【解决方案1】:

查看string formatting 上的文档,它可以让您控制:

>>> def formatted(x, y, z):
       # column 1 is 10 chars wide, left justified
       # column 2 is 5 chars wide
       # column3 is whatever is left.
...    print "{:<10}{:<5}{}".format(x, y, z)

>>> formatted(1, "f", "bar")
>>> formatted(10, "fo", "bar")
>>> formatted(100, "foo", "bar")

输出

1         f    bar
10        fo   bar
100       foo  bar

...保持列宽。

所以在你的例子中,而不是

   for item in incorrectindex:
        print(item+1,"     ",correctanswers[item],"    ",studentanswers[item])

类似:

for item in incorrect index:
    print("{:<5}{:<10}{}".format(item+1, correctanswers[item], studentanswers[item])

【讨论】:

  • 对,但我如何将它合并到 for 循环中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 2016-02-10
  • 1970-01-01
相关资源
最近更新 更多