繁体   English   中英

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

[英]Formatting text to be justified in Python 3.3 with .format() method

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

金额可以这样形成:

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

请参见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
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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM