加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用.format()方法将文本格式化为Python 3.3

发布时间:2020-12-16 23:02:14 所属栏目:Python 来源:网络整理
导读:我是 Python的新手,并尝试使用一些示例脚本.我正在做一个简单的收银机类型的事情,但我想要证明或右对齐输出,使其看起来像这样: subTotal = 24.95tax = subTotal * 0.0725total = subTotal + taxpaid = 30change = paid-totalprint("The subtotal was: $",su
我是 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))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读