2013-04-23 8 views
10

Jestem nowy w Pythonie i próbuję pracować nad przykładowymi skryptami. Robię prosty rodzajem gotówki rejestr rzeczy, ale chcę usprawiedliwiać lub prawo wyrównać wyjście tak, że wygląda mniej więcej tak:Formatowanie tekstu do usprawiedliwienia w Pythonie 3.3 za pomocą metody .format()

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) 

Wiem, że mógłbym uprościć to o wiele mniej instrukcji print, ale chciałem, żeby łatwiej było zobaczyć, co próbuję zrobić.

Chcę, żeby coś takiego wypisało, zauważ, że kwoty w dolarach są wyrównane i że nie ma miejsca między kwotą $ a dolarem. Nie wiem, jak zrobić te dwie rzeczy.

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

Próbowałem czytanie docs Pythona dla metody formatu, ale nie widzę żadnych przykładów, co Format Specyfikatory może być używany do robienia pewnych rzeczy. Z góry dziękuję za pomoc.

+1

Jeżeli 'całkowity = SUBTOTAL + tax'? – TerryA

+0

Tak, przepraszam za tę literówkę. Poprawiłem to. – SISYN

Odpowiedz

7

Kwota może być sformatowany tak:

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

Możesz dodać dopełnienie do łańcucha, na przykład o szerokości 20:

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

można prawo wyrównać łańcuch, na przykład o szerokości 7:

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

Kładzenie to wszystko razem:

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

Jeśli znasz maksymalne rozmiary tekstu i liczb, można zrobić

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

To staje się trudniejsze, jeśli nie są one znane z wyprzedzeniem. Oto podejście, zakładając names i values są listy:

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

Wyjście

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

Można również uzyskać wymaganego odstępu tak:

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

Ilości nie są wyrównane do prawej w Twoim rozwiązaniu. –

2

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

wyjściowa:

The subtotal was: $24.95 
The tax was:  $1.81 
The total was:  $26.76 
The customer paid: $30.00 
Change due:   $3.24 
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)) 
+0

OP poprosił o metodę '.format()'. –

Powiązane problemy