我想将"$"和totalTransactionCost一起移动到字段的右侧。
我的当前代码是:print(f"所有交易总成本:${totalTransactionCost:>63,.2f}")
该代码能够将totalTransactionCost移动到字段的右侧,但如何同时包含"$"?
您可以使用嵌套的 f-strings,将格式化分为两个步骤:首先,将数字格式化为逗号分隔的两位小数字符串,并附加 $
,然后填充整个字符串以获得前导空格。
>>> totalTransactionCost = 10000
>>> print(f"Total Cost Of All Transactions: {f'${totalTransactionCost:,.2f}':>64}")
Total Cost Of All Transactions: $10,000.00
f-string提供了灵活性。
如果货币是由系统确定的,locale
允许利用系统的设置:LC_MONETARY表示货币
以下是f-string
的演示
## input value or use default
totalTransactionCost = input('enter amount e.g 50000') or '50000'
## OP's code:
#print(f"Total Cost Of All Transactions: ${totalTransactionCost:>63,.2f}")
## f-string with formatting
## :,.2f || use thousand separator with 2 decimal places
## :>63 || > aligns right with 63 spaces
## :< || < aligns left
## { ... :,.2f} apply to inner f-string value
## {f'${ ... }':>64} || apply to outer f-string value
print(f'|Total Cost of All Transactions|: {f"${int(totalTransactionCost):,.2f}":>64}')
## Note that the inner and outer uses different escapes.
## The order doesn't matter though. Here, inner is " and outer is '.
|enter amount e.g 50000| 750000
Total Cost of All Transactions: $750,000.00