在Python中格式化右对齐

时间:2013-02-01 01:45:02

标签: python format

嘿伙计们,所以我在Python课程的介绍中有一个作业,我的老师注意到(他还没有解释)输出的某一部分必须通过format()函数进行右对齐。

到目前为止,我已经了解了一些关于格式的内容,例如:

print(format(12345.6789,'.2f'))
print(format(12345.6789,',.2f'))
print('The number is ',format(12345.6789,'10,.3f'))
print(format(123456,'10,d'))

我理解这些很好,但这是我教授在我的课程中想要的。

这需要正确的理由:

    Amount paid for the stock:      $ 350,000
    Commission paid on the purchase:$  27,000
    Amount the stock sold for:      $ 350,000 
    Commission paid on the sale:    $   30,00
    Profit (or loss if negative):   $ -57,000

这些数字不正确^我忘记了实际值,但你明白了。

这是我已经拥有的代码。

#Output
print("\n\n")
print("Amount paid for the stock:      $",format(stockPaid,',.2f'),sep='')
print("Commission paid on the purchase:$",format(commissionBuy,',.2f'),sep='')
print("Amount the stock sold for:      $",format(stockSold,',.2f'),sep='')
print("Commission paid on the sale:    $",format(commissionSell,',.2f'),sep='')
print("Profit (or loss if negative):   $",format(profit,',.2f'),sep='')

那么我怎样才能让这些值正确地打印出来,而其余的字符串在左对齐之前呢?

感谢您的帮助,你们一如既往地棒极了!

2 个答案:

答案 0 :(得分:0)

尝试使用它 - 但它在文档中。您将需要应用您已经获得的任何其他格式。

>>> format('123', '>30')
'                           123'

答案 1 :(得分:0)

这个问题几乎与Align Left / Right in Python重复有一个修改,让它适合你(以下代码是Python 3.X兼容):

# generic list name with generic values
apples = ['a', 'ab', 'abc', 'abcd']

def align_text(le, ri):
    max_left_size = len(max(le, key=len))
    max_right_size = len(max(ri, key=len))
    padding = max_left_size + max_right_size + 1

    return ['{}{}{}'.format(x[0], ' '*(padding-(len(x[0])+len(x[1]))), x[1]) for x in zip(le, ri)]

for x in align_text(apples, apples):
    print (x)

"".format()语法用于将字符串中的占位符替换为您提供的参数,其文档为Python Docs String Formatter。当你创建混合了变量的字符串时,我无法强调这是多么令人惊讶。

这将要求您将左右值放在单独的列表中,但是,从您的示例中可能是:

left_stuff = [
        "Amount paid for the stock:      $",
        "Commission paid on the purchase:$",
        "Amount the stock sold for:      $",
        "Commission paid on the sale:    $",
        "Profit (or loss if negative):   $"]

right_stuff = [
        format(1,',.2f'),
        format(1,',.2f'),
        format(1,',.2f'),
        format(1,',.2f'),
        format(1,',.2f')]

输出结果为:

Amount paid for the stock:      $ 1.00
Commission paid on the purchase:$ 1.00
Amount the stock sold for:      $ 1.00
Commission paid on the sale:    $ 1.00
Profit (or loss if negative):   $ 1.00

您可以通过移除函数中的+1或将$放在右侧来消除$之间的空间。

相关问题