用Python自动化无聊的东西,第六章实践项目

问题描述 投票:0回答:1

我对《用Python自动化无聊的东西》一书中第6章练习项目的解决方法有一个简短的问题。我应该写一个函数,以列表的形式接收数据。

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

并打印出下面的表格,每一列都是右对齐的。

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

问题是,我的代码:

def printTable(table):
    colsWidths = [0]*len(table) #this variable will be used to store width of each column
    # I am using max function with key=len on each list in the table to find the longest string --> it's length be the length of the colum
    for i in range(len(table)):
        colsWidths[i] = len(max(table[i], key = len)) # colsWidths = [8,5,5]
    # Looping through the table to print columns
    for i in range(len(table[0])):
        for j in range(len(table)):
            print(table[j][i].rjust(colsWidths[j], " "), end = " ")
        print("\n")

打印出的表格中,每行之间都有过多的空行。

printTable(tableData)

  apples Alice  dogs

 oranges   Bob  cats

cherries Carol moose

  banana David goose

我知道这和程序末尾写的print语句有关 但如果没有它,所有的东西都会被打印出来。所以我的问题是,有没有办法把表中的那些空行去掉?

python for-loop newline
1个回答
2
投票

替换 print("\n")print()

print 默认情况下会打印一个换行符,这就是默认的 end 参数是。

当你做 print("\n")你实质上是在打印两行新字。

© www.soinside.com 2019 - 2024. All rights reserved.