如何用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

