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

如何用Python读取并格式化特定格式文本文件以匹配现有代码

Got it, let's tackle this formatting step by step. You've already got the file content loaded and the # characters handled, so here's how to get the output aligned perfectly with your existing header:

First, let's recap the setup. Assuming you've read the file content into a string (like content = "hammer#9.95 saw#20.15 shovel#35.40"), start by splitting that string into individual item-price pairs:

# Split the content into separate item entries
items = content.split()

Then, use the same string formatting logic as your header to print each line. Your header uses left-aligned (<) for "Item" (width 10) and right-aligned (>) for "Cost" (width 17). We'll mirror that for each item, adding the $ symbol to the cost:

# Your existing header code
print('{0: <10}'.format('Item'), '{0: >17}'.format('Cost'), sep='')

# Loop through each item and format the output
for entry in items:
    # Split each entry into name and cost (works directly with the original # separator)
    item_name, item_cost = entry.split('#')
    # Format and print: left-align name (10 width), right-align cost with $ (17 width)
    print('{0: <10}'.format(item_name), '{0: >17}'.format(f'${item_cost}'), sep='')

Running this will give you exactly the output you want:

Item        Cost
hammer      $9.95
saw         $20.15
shovel      $35.40

A quick note: If you already replaced the # with another separator (like a space) earlier, just adjust the split('#') part to match whatever character you used instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:09:25