理解.format方法

时间:2018-05-15 22:47:19

标签: python-3.x function printing format

作为作业的一部分,我写了一个小程序来保持银行余额:

get_attribute("innerHTML")

我对def setBalance(amt): # Defines but does not print the value of the starting balance global balance balance = amt def printBalance(): # Displays current balance as a money value with a heading global balance print("---------------------------") print("Current balance is $%.2f" % balance) def printLedgerLine(date, amount, details): # with items (and the balance) spaced and formatted global balance print("{0:<15}{2:<20}${1:>8.2f} ${3:>8.2f}".format(date, details, amount, balance)) def deposit (date, details, amount): # Alter the balance and print ledger line global balance balance += amount printLedgerLine(date, details, amount) def withdraw(date, details, amount): # Alter the balance and print ledger line global balance balance -= amount printLedgerLine(date, details, amount) #""" setBalance(500) printBalance() withdraw("17-12-2012", "BP - petrol", 72.50) withdraw("19-12-2012", "Countdown", 55.50) withdraw("20-12-2012", "munchies", 1.99) withdraw("22-12-2012", "Vodafone", 20) deposit ("23-12-2012", "Income", 225) withdraw("24-12-2012", "Presents", 99.02) #deposit("25-12-2012", "Holiday pay", 102.22) printBalance() #""" 函数中的print语句感到困惑。它工作正常,打印

printLedgerLine

--------------------------- Current balance is $500.00 17-12-2012 BP - petrol $ 72.50 $ 427.50 19-12-2012 Countdown $ 55.50 $ 372.00 20-12-2012 munchies $ 1.99 $ 370.01 22-12-2012 Vodafone $ 20.00 $ 350.01 23-12-2012 Income $ 225.00 $ 575.01 24-12-2012 Presents $ 99.02 $ 475.99 --------------------------- Current balance is $475.99 语句为

print

但我认为print("{0:<15}{2:<20}${1:>8.2f} ${3:>8.2f}".format(date, details, amount, balance))方法的工作方式是每个{0},{1}等与.format中的每个参数匹配。那么为什么呢?

.format()

打印

print("{0:<15}{1:<20}${2:>8.2}           ${3:>8.2f}".format(date, details, amount, balance))

?它与--------------------------- Current balance is $500.00 17-12-2012 72.5 $ BP $ 427.50 19-12-2012 55.5 $ Co $ 372.00 20-12-2012 1.99 $ mu $ 370.01 22-12-2012 20 $ Vo $ 350.01 23-12-2012 225 $ In $ 575.01 24-12-2012 99.02 $ Pr $ 475.99 --------------------------- Current balance is $475.99 的定义中的参数顺序有关吗?

0 个答案:

没有答案