以表格形式打印

时间:2014-12-17 11:54:33

标签: python python-2.7 formatting output

如何以表格形式打印?

listex = range(nOfYears)
counter = 1
for i in listex:
        if i ==0:

            print counter, '\t',startingBalance,'\t', amountofinterest, '\t', next_balance 
            previous_balance = next_balance
            total_interest +=amountofinterest
        else:
            counter += 1

            amountofinterest = previous_balance*interestRate
            total_balance = previous_balance+amountofinterest
            print counter, '\t', previous_balance,'\t', amountofinterest, '\t', total_balance
            previous_balance = total_balance
            total_interest += amountofinterest 
print '\n', "TOTAL BALANCE IS :", previous_balance
print "TOTAL AMOUNT OF INTEREST IS %.2f:" %(total_interest)

1 个答案:

答案 0 :(得分:0)

如果你想在控制台中以表格的形式打印它,你应该尝试使用非常容易使用的tabulate模块。 (https://pypi.python.org/pypi/tabulate) 简单的例子:

from tabulate import tabulate
table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
         ["Moon",1737,73.5],["Mars",3390,641.85]]
print tabulate(table)
#-----  ------  -------------
#Sun    696000     1.9891e+09
#Earth    6371  5973.6
#Moon     1737    73.5
#Mars     3390   641.85
#-----  ------  -------------

如果要使用\t字符分隔列,则应检查csv模块和csv writer。