我有一个简短的问题,关于第6章实践项目的解决方案,在“用Python自动化无聊的东西”一书中。我应该编写一个函数,以列表的形式获取数据:
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语句有关,但是没有它,所有的东西都会被打印出来。所以我的问题是,有没有办法从表中删除那些空行?
发布于 2020-05-04 10:29:25
将print("\n")替换为print()
默认情况下,print打印换行符,这就是end参数的默认值。
当您执行print("\n")时,实际上您正在打印两条新行。
https://stackoverflow.com/questions/61590070
复制相似问题