在Python中格式化右对齐

-2 投票
2 回答
5204 浏览
提问于 2025-04-17 14:23

大家好,我在Python入门课上有一个作业要交,我老师提到(他还没解释清楚)输出的某个部分需要用format()函数进行右对齐。

到目前为止,我学到了一些关于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

试试这个 - 其实在文档里有说明。不过,你可能还需要加上其他你已经有的格式设置。

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

这个问题几乎和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文档中的字符串格式化。我想强调的是,当你在创建包含变量的字符串时,这个功能是多么强大。

不过,这需要你把左边和右边的值放在不同的列表里,根据你的例子,应该是这样的:

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,或者把$符号放在右边,来去掉$之间的空格。

撰写回答