Python 3.x Python3与'$';

Python 3.x Python3与'$';,python-3.x,formatting,Python 3.x,Formatting,这周我刚开始学习Python,我遇到了一些行格式的问题。我试图插入一个带有计算值的“$”,我试图插入带有一个新的{}集的“$”,以及这里的{{$:>{}.2f}(基于谷歌搜索建议),但是我不断得到错误 我正在使用Google Collab来运行代码 def预算计算(金钱、租金、食物、电话、汽油、额外收入): 宽度=35 价格/宽度=10 项目宽度=宽度-价格宽度 收入=总和(周收入)+额外收入 费用=总额(信用卡)+租金+电话+食品+煤气+公用事业 税后=收入*0.84 #税后仪器=str(税

这周我刚开始学习Python,我遇到了一些行格式的问题。我试图插入一个带有计算值的“$”,我试图插入带有一个新的{}集的“$”,以及这里的
{{$:>{}.2f}
(基于谷歌搜索建议),但是我不断得到错误

我正在使用Google Collab来运行代码

def预算计算(金钱、租金、食物、电话、汽油、额外收入):
宽度=35
价格/宽度=10
项目宽度=宽度-价格宽度
收入=总和(周收入)+额外收入
费用=总额(信用卡)+租金+电话+食品+煤气+公用事业
税后=收入*0.84
#税后仪器=str(税后)
毛额=‘税前收入:’#+str(收入)
税后收入=‘税后收入:’税后收入
税款支付=到期税款:#+str(收入*.16)
储蓄=税后-费用
总计='剩余资金:'#+'$'+str(储蓄)
费用总额='总费用'#+str([费用])
行=“{{:{}}}{{:>{}.2f}}}”。格式(项目宽度、价格宽度)
打印(行格式(总收入)
打印(行格式(税款支付,(收入*0.16)))
打印(行格式(税后、税后))
打印(行格式(费用总额,费用))

打印(line.format(total,savings))
我认为它抛出的错误将是
keyerror
,这是因为混乱的字符串格式



Python3.6+字符串插值是推荐的字符串格式设置方法,因为它具有很高的可读性

最好的办法是:

打印(f'税前货币:{income}')

print(f'到期税款:{income*0.16}')

打印(f'税后收入:{税后})

print(f'Total expenses:{expenses}')

print(f'剩余的钱:{savings}')


但是,如果您只想使用
$
字符串格式,那么您应该尝试回答以下问题

您会遇到哪些错误?您想要的输出是什么?您还可以消除字符串不必要的内存存储
def budget_calc(money, rent, food, phone, gas, extra_income):
  width = 35
  price_width = 10
  item_width = width - price_width
  income = sum(weekly_income) + extra_income
  expenses = sum(credit_cards) + rent + phone + food + gas + utilities

  after_tax =income*0.84
  #after_tax_instr = str(after_tax)

  gross = 'Money before tax:'           #+ str(income)

  post_tax= 'Post tax income:'          #+after_tax_instr

  tax_payment ='Taxes due:'             #+str(income*.16) 

  savings = after_tax - expenses

  total = 'Money left over:'            #+'$'+str(savings)

  expense_total = 'Total expenses'      #+str([expenses])


  # You can specify the width integer instead of formating 
  line = "{0:<25} ${1:.2f}"
  
  print(line.format(gross, income))
  print(line.format(tax_payment, (income*0.16)))
  print(line.format(post_tax, after_tax))
  print(line.format(expense_total, expenses))
  print(line.format(total, savings))
Money before tax:          $33510.00
Taxes due:                 $5361.60
Post tax income:           $28148.40
Total expenses             $762.00
Money left over:           $27386.40