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

Python等间距同行打印两词及收据格式化输出技术问询

Python 打印相关问题解答

Hey there! Let's tackle your two Python questions one by one:


问题1:如何实现两个单词在同一行且等间距打印

有几种灵活的方法可以达成这个需求,我给你分享几个常用的:

  • 使用f-string对齐(推荐):这种方式最直观,你可以给第一个单词设置固定宽度,不足的部分用空格填充,这样第二个单词的位置始终保持一致:

    word1 = "Apple"
    word2 = "$5.99"
    # <15 表示左对齐,占用15个字符宽度
    print(f"{word1:<15}{word2}")
    # 输出:Apple           $5.99
    
  • 使用str.format()方法:如果你的Python版本低于3.6,f-string不支持的话,可以用这个替代,原理一样:

    print("{:<15}{}".format("Banana", "$3.49"))
    # 输出:Banana          $3.49
    
  • 手动添加固定空格:如果是特定场景下的固定间距,直接拼接空格也能行,但灵活性差一些:

    print("Orange" + " " * 10 + "$4.29")
    # 输出:Orange          $4.29
    

问题2:调整收据输出为指定样式

先看你想要的目标输出:

-------- Final Receipt --------
Milk, 2 Litres $ 2
Potatoes $ 7.5
Sugar $ 3.5

基于你现有的代码,我们只需要添加顶部分隔线,并统一商品行的输出格式即可。这里假设你的product_in_basket字典结构大概是这样(根据现有代码逻辑推测):

product_in_basket = {
    "item1": [1, "Milk, 2 Litres", 2],
    "item2": [2, "Potatoes", 7.5],
    "item3": [3, "Sugar", 3.5],
    "total": [13.0]  # 这是你用[:-1]排除的最后一个值
}

修改后的代码如下:

# 先打印顶部的分隔线
print("-------- Final Receipt --------")

# 遍历商品数据,保持你原有的遍历逻辑
for mydata in zip(*list(product_in_basket.values())[:-1]):
    product_name = mydata[1]
    price = mydata[2]
    # 用f-string统一输出格式
    print(f"{product_name} $ {price}")

运行这段代码就能得到你想要的样式啦!如果想让价格部分更对齐(比如所有$符号在同一列),可以优化一下,先计算最长的商品名长度,再做对齐:

print("-------- Final Receipt --------")

# 先计算所有商品名的最大长度,用于对齐
products = list(zip(*list(product_in_basket.values())[:-1]))
max_name_len = max(len(item[1]) for item in products)

for mydata in products:
    product_name = mydata[1]
    price = mydata[2]
    # 让商品名左对齐,占满max_name_len宽度,保证$符号对齐
    print(f"{product_name:<{max_name_len}} $ {price}")

优化后的输出会更规整:

-------- Final Receipt --------
Milk, 2 Litres $ 2
Potatoes       $ 7.5
Sugar          $ 3.5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:51:29