Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用.format()方法格式化Python 3.3中要对齐的文本_Python_Python 3.x - Fatal编程技术网

使用.format()方法格式化Python 3.3中要对齐的文本

使用.format()方法格式化Python 3.3中要对齐的文本,python,python-3.x,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: $

我是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)
"${:.2f}".format(amount)
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)
我知道我可以用更少的打印语句来简化这个过程,但我只是想让它更容易看到我在做什么

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

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

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

如果您知道文本和数字的最大大小,您可以这样做

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

金额的格式如下所示:

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)
"${:.2f}".format(amount)
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)
您可以为字符串添加填充,例如宽度为20:

"{:20s}".format(mystring)
您可以右对齐字符串,例如宽度为7:

"{:>7s}".format(mystring)
综上所述:

s = "The subtotal was:"
a = 24.95
print("{:20s}{:>7s}".format(s, "${.2f}".format(a))
您还可以获得如下所示的所需间距:

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)
"${:.2f}".format(amount)
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)
maxLen=max(len(t)表示文本中的t)
对于zip中的t、v(文本、值):
打印str(“{0:请参见


应该
total=subTotal+tax
?是的,对不起,我已经更正了。