You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在数字前添加$并保持文本居中?Python格式化问题求助

解决方法

问题出在你把$和价格分开格式化了,导致$和价格之间出现多余空格。正确的做法是把$和价格合并成一个整体,再和商品名一起排版,同时让商品名左对齐、价格(含$)右对齐,这样就能保证排版整齐且无多余间距。

修改后的核心代码片段

for item, price in special_items.items():
    # 将$和价格合并为一个字符串,再分别对齐商品名和价格
    price_str = f"${price:.2f}"
    x = f"{item:<20} {price_str:>10}"
    centered_text(x)

完整修改后的代码

def centered_text(text: str = " ", width: int = 50) -> None:
    """
    text: 要打印的文本
    width: 文本最大字符宽度
    return: 打印居中后的文本
    """
    if len(text) > width - 4:
        print("无效输入,超出宽度{}个字符".format((len(text) - width)))
    if text == "*":
        print("*" * width)
    else:
        centered = text.center(width - 4)
        output_string = "**{}**".format(centered)
        print(output_string)


cart = []
special_items = {'Metal pipe': 5.99,
                 'Large table': 30.99,
                 'Battle ship': 12.99,
                 'Gaming PC': 1599.99,
                 '24-Pack of water': 19.99,
                 'Dog chew toy': 4.99,
                 'Space Ice cream': 8.99,
                 'Nerf gun': 10.99,
                 'Pokemon cards': 6.99,
                 'Desk': 49.99}

print("欢迎来到亚马逊!我们为您准备了一些特价商品,清单如下:")

centered_text("*")
for item, price in special_items.items():
    price_str = f"${price:.2f}"
    x = f"{item:<20} {price_str:>10}"
    centered_text(x)
centered_text("*")

修改说明

  1. 合并$和价格:先把价格格式化为带$的完整字符串(如$5.99),避免$和价格被分开格式化产生多余空格。
  2. 双对齐排版:用:<20让商品名左对齐并固定占20个字符宽度,用:>10让带$的价格右对齐并固定占10个字符宽度,中间自动填充空格,保证每行排版整齐。
  3. 保留原有的centered_text函数,它负责将整行文本居中并添加前后的**边框,确保整体布局符合要求。

运行修改后的代码即可得到你期望的输出效果。

内容的提问来源于stack exchange,提问作者TypicalTy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 06:06:20