首页 > 解决方案 > 用 $ 打印它,如使用 python 格式所示

问题描述

我需要将 $ 添加到价格部分,如此处所示 1

如何使用 f-string 做到这一点

for name, shares, price, change in report:

print(f'{name:>10s} {shares:>10d}  {price:>10.2f} {change:>10.2f}')

标签: pythonformatting

解决方案


report = [
    ['AA', 100, 9.22, -22.98],
    ['IBM', 50, 106.28, 15.18]
]

for name, shares, price, change in report:
    price = f'${price:.2f}'
    print(f'{name:>10} {shares:>10d}  {price:>10} {change:>10.2f}')

印刷:

    AA        100       $9.22     -22.98
   IBM         50     $106.28      15.18

推荐阅读