使用.format()方法格式化要在Python3.3中对齐的文本

2024-05-28 18:57:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,正在尝试编写一些示例脚本。我正在做一个简单的收银机类型的事情,但我想调整或右对齐输出,使其看起来像这样:

subTotal = 24.95
tax = subTotal * 0.0725
total = subTotal + tax
paid = 30
change = paid-total
print("The subtotal was: $",subTotal)
print("The tax was: $",tax)
print("The total was: $",total)
print("The customer paid: $",paid)
print("Change due: $",change)

我知道我可以用更少的打印语句来简化这个过程,但我只是想更容易地看到我在做什么。

我希望它输出类似这样的内容,注意美元金额都是对齐的,并且美元和美元金额之间没有空格。我不知道怎么做这两件事。

The subtotal was:   $24.95
The tax was:         $1.81
The total was:      $26.76
The customer paid:  $30.00
Change due:          $3.24

我试着阅读Python文档中的format方法,但是我没有看到任何关于可以使用什么格式说明符来做某些事情的例子。提前谢谢你的帮助。


Tags: thecustomerchange事情金额totalduetax
3条回答

金额的格式如下:

"${:.2f}".format(amount)

可以向字符串添加填充,例如宽度为20:

"{:20s}".format(mystring)

可以将字符串右对齐,例如宽度为7:

"{:>7s}".format(mystring)

把这些放在一起:

s = "The subtotal was:"
a = 24.95
print("{:20s}{:>7s}".format(s, "${.2f}".format(a))

如果你知道文本和数字的最大大小,你可以

val_str = '${:.2f}'.format(val)
print('{:<18} {:>6}'.format(name+':', val_str))

如果事先不知道这些会变得更棘手。这里有一种方法,假设namesvalues是列表:

value_format = '${:.2f}'.format
name_format = '{}:'.format
values_fmt = [value_format(val) for val in values]
names_fmt = [name_format(name) for name in names]
max_value_len = max(len(x) for x in values_fmt)
max_name_len = max(len(x) for x in names_fmt)
for name, val in zip(names_fmt, values_fmt):
    print('{:<{namelen}} {:>{vallen}}'.format(name, val,
        namelen=max_name_len, vallen=max_value_len))
subTotal = 24.95
tax = subTotal * 0.0725
total = subTotal + tax 
paid = 30
change = paid-total

text  = [ 
"The subtotal was:", "The tax was:", "The total was:",
"The customer paid:", "Change due:"
]
value = [ subTotal, tax, total, paid, change ]

for t,v in zip(text, value):
    print "{0:<25} ${1:.2f}".format(t, v)

输出

The subtotal was:         $24.95
The tax was:              $1.81
The total was:            $26.76
The customer paid:        $30.00
Change due:               $3.24

您还可以获得所需的间距,如下所示:

maxLen = max(len(t) for t in text)  
for t,v in zip(text, value):
    print str("{0:<" + str(maxLen) + "} ${1:.2f}").format(t, v)

相关问题 更多 >

    热门问题