Python - 删除嵌套循环中一行中的第一个单词

时间:2013-10-31 07:43:19

标签: python string for-loop formatting output

我想生成以下输出:

20 $ 476321.30  $ 923268.18  $ 1859015.31  $ 3840898.15

使用此代码:

for age in range(20, 70, 5):
    for percentage in range(4, 12, 2):
        result = calc_final_balance(age, amount_saved, percentage)
        print(age, "\t $" + format(result, '.2f').rjust(10), end="")
    print()

但问题是,年龄总是在金额后打印:

20 $ 476321.3020  $ 923268.1820  $ 1859015.3120  $ 3840898.15

1 个答案:

答案 0 :(得分:4)

您可以轻松完成此操作。只需在您的第一个“更高”循环中打印它:

for age in range(20, 70, 5):
    print(age, end=" ") #end is space
    for percentage in range(4, 12, 2):
        result = calc_final_balance(age, amount_saved, percentage)
        print("\t $" + format(result, '.2f').rjust(10), end=" ")
    print()

这样会产生类似的东西:

20 $ 476321.30  $ 923268.18  $ 1859015.31  $ 3840898.15
70 $ someamount $ someamount $ someamount $ someamount
5 $ someamount $ someamount $ someamount $ someamount