使用.format()方法在Python 3.3中格式化文本

时间:2013-04-23 01:06:56

标签: python python-3.x

我是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文档,但我没有看到任何格式说明符可用于执行某些操作的示例。提前感谢您的帮助。

5 个答案:

答案 0 :(得分:9)

金额可以这样形成:

"${:.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))

答案 1 :(得分:4)

如果你知道文字和数字的最大尺寸,你可以

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))

答案 2 :(得分:4)

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)

答案 3 :(得分:2)

请参阅http://docs.python.org/2/library/string.html#grammar-token-width

def myformat(name, value):
    return "{:<18} {:>6}".format(name, "${:.2f}".format(value))
print(myformat("The subtotal was:", subTotal))
print(myformat("The tax was:", tax))
print(myformat("The total was:", total))
print(myformat("The customer paid:", paid))
print(myformat("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

答案 4 :(得分:1)

subTotal = 24.95
tax = subTotal * 0.0725
total = subTotal + tax
paid = 30
change = paid-total
print("The subtotal was: %8s" % ("$%.2f" % subTotal))
print("The tax was:      %8s" % ("$%.2f" % tax))
print("The total was:    %8s" % ("$%.2f" % total))
print("The customer paid:%8s" % ("$%.2f" % paid))
print("Change due:       %8s" % ("$%.2f" % change))