如何在 Python 中右对齐打印货币符号和 n 位十进制数

How to print currency symbol and an n-digit decimal number right aligned in Python

我正在制作一个 EMI 计算器,它会在显示每月 EMI 后显示摊销 table。

如何右对齐货币符号和任何 n 位十进制数?

我尝试使用 '{0}{1:5.2f}'.format(rupee, amount) 右对齐货币符号和金额,但它没有解决说明格式字符串不正确的问题。

金额为小数点后2位以上的浮点数,需要四舍五入到小数点后2位。

这是显示 4 个金额值的代码(我使用 INR 作为货币符号):

rupee = chr(8377)
print('{0}{1:.2f}'.format(rupee, amount1))
print('{0}{1:.2f}'.format(rupee, amount2))
print('{0}{1:.2f}'.format(rupee, amount3))
print('{0}{1:.2f}'.format(rupee, amount4))

需要在此示例代码中进行一些编辑以使货币符号和金额右对齐,但我无法弄清楚。

实际输出:

.07
.34
3.08
.98

预期输出:

  .07
 .34
3.08
  .98

由于无法直接从键盘输入卢比符号,所以将$符号作为货币符号。

如果您知道输出中的最大字符数,那么您可以执行如下操作。有关各种可用的格式说明符,请参阅 Format Specification Mini-Language

amounts = ['.07', '.34', '3.08', '.98']

for amount in amounts:
    print('{:>8}'.format(amount))

# OUTPUT
#   .07
#  .34
# 3.08
#   .98

稍微扩展之前的答案:

rupee = u'\u20B9'
amounts = [12345.67, 1.07, 22.34, 213.08, 4.98]

for amount in amounts:
    print('{:>10}'.format(rupee + '{:>.2f}'.format(amount)))

输出:

 ₹12345.67
     ₹1.07
    ₹22.34
   ₹213.08
     ₹4.98