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

2024-09-26 17:46:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

下面是显示4个金额值的代码(我用印度卢比作为货币符号):

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))

需要在这个示例代码中进行一些编辑,以右对齐货币符号和金额,但我无法确定这一点。在

实际产量:

^{pr2}$

预期产量:

  $1.07
 $22.34
$213.08
  $4.98

接受$符号作为货币符号,因为卢比符号不能直接从键盘输入。在


Tags: 字符串代码format声明格式货币符号金额
2条回答

把前面的答案再延伸一点:

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)))

输出:

^{pr2}$

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

amounts = ['$1.07', '$22.34', '$213.08', '$4.98']

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

# OUTPUT
#   $1.07
#  $22.34
# $213.08
#   $4.98

相关问题 更多 >

    热门问题