pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]
for i, (item, count) in enumerate(pantry): print('#%d: %-10s = %.2f' % (i, item, count))
What It Prints (Correctly)
#0: avocados = 1.25#1: bananas = 2.50#2: cherries = 15.00
#%d → prints the index number (0, 1, 2).
%-10s → left-aligns the string (item name) in a field 10 characters wide. Example: "bananas " (adds spaces to align neatly).
%.2f → prints the number with 2 decimal places.
So the = sign belongs in the format string itself:
'%-10s = %.2f'
✅ If you run the exact code above, you will not see separate lines with just the numbers.Instead, you’ll see neatly aligned item + count pairs.
👉 Do you want me to also show you the f-string version (more modern & cleaner than % formatting)?
yes
Perfect 👍 f-strings make this much cleaner and easier to read.
Here’s your same example rewritten with f-strings:
pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]
for i, (item, count) in enumerate(pantry): print(f"#{i}: {item:<10} = {count:.2f}")
Output
#0: avocados = 1.25#1: bananas = 2.50#2: cherries = 15.00
Explanation
{item:<10} → left-aligns the string in a field 10 characters wide.
{count:.2f} → formats the number with 2 decimal places.
f"..." → directly embeds variables into the string (no % or .format() needed).
>>> pantry = [
... ('avocados', 1.25),
... ('bananas', 2.5),
... ('cherries', 15),
... ]
...
... for i, (item, count) in enumerate(pantry):
... print(f"{i} {item} = {count}")
...
0 avocados = 1.25
1 bananas = 2.5
2 cherries = 15
Great! Let’s align the numbers in a column so that the decimal points line up neatly.
We can give the number a fixed width in addition to 2 decimal places.Example
pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]
for i, (item, count) in enumerate(pantry): print(f"#{i}: {item:<10} = {count:6.2f}")
Output
#0: avocados = 1.25#1: bananas = 2.50#2: cherries = 15.00
Explanation
{count:6.2f}
6 → total width (including digits, decimal point, and spaces).
.2f → 2 decimal places.
So shorter numbers get padded with spaces on the left, making the column line up.
👉 If you want even bigger alignment (for larger prices like 1234.56), you can increase the width, e.g. {count:8.2f}.
Would you like me to also show how to make this into a pretty table style (like a shopping list)?
yes
Perfect 👍 Let’s make your pantry print like a neat shopping list table.
We’ll use f-strings with alignment for each column.Example: Pretty Table
pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]
# Print headerprint(f"{'Index':<5} {'Item':<12} {'Price':>8}")print("-" * 30)
# Print rowsfor i, (item, count) in enumerate(pantry): print(f"{i:<5} {item:<12} {count:>8.2f}")
Output
Index Item Price------------------------------0 avocados 1.251 bananas 2.502 cherries 15.00
Explanation
{'Index':<5} → left-align “Index” in 5 spaces.
{'Item':<12} → left-align item names in 12 spaces.
{'Price':>8} → right-align prices in 8 spaces (so decimals line up).
"—" * 30 → prints a line separator.
👉 Would you like me to also show you how to do this using the tabulate library (gives a professional table format
yes
Awesome 🚀 The tabulate library makes this super easy and looks very professional.
First, you’ll need to install it (only once):
pip install tabulate
Example with tabulate
from tabulate import tabulate
pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]
# Prepare table data with headerstable = [(i, item, count) for i, (item, count) in enumerate(pantry)]
print(tabulate(table, headers=["Index", "Item", "Price"], floatfmt=".2f"))
Output (default style)
Index Item Price------- ---------- ------ 0 avocados 1.25 1 bananas 2.50 2 cherries 15.00
You can also change table styles:
print(tabulate(table, headers=["Index", "Item", "Price"], tablefmt="grid", floatfmt=".2f"))
Output:
+---------+-----------+--------+| Index | Item | Price |+---------+-----------+--------+| 0 | avocados | 1.25 || 1 | bananas | 2.50 || 2 | cherries | 15.00 |+---------+-----------+--------+
Other table options: "plain", "fancy_grid", "github", "pipe", "html", etc.
👉 Do you want me to show you how to export this table directly to Excel/CSV/Markdown after formatting?
yes
Perfect ✅ Let’s extend this so you can export your pantry table into common formats like Excel, CSV, or Markdown.1. Export to CSV
import csv
pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]
with open("pantry.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["Index", "Item", "Price"]) for i, (item, count) in enumerate(pantry): writer.writerow([i, item, f"{count:.2f}"])
👉 Creates a pantry.csv file that opens in Excel or any text editor.2. Export to Excel (.xlsx)
from openpyxl import Workbook
pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]
wb = Workbook()ws = wb.activews.append(["Index", "Item", "Price"])
for i, (item, count) in enumerate(pantry): ws.append([i, item, round(count, 2)])
wb.save("pantry.xlsx")
👉 Creates a nice Excel sheet with rows and columns.3. Export to Markdown Table
from tabulate import tabulate
pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]
table = [(i, item, count) for i, (item, count) in enumerate(pantry)]
markdown = tabulate(table, headers=["Index", "Item", "Price"], tablefmt="github", floatfmt=".2f")
with open("pantry.md", "w") as f: f.write(markdown)
print(markdown)
Output inside pantry.md:
| Index | Item | Price ||---------|-----------|---------|| 0 | avocados | 1.25 || 1 | bananas | 2.50 || 2 | cherries | 15.00 |
✨ Now you can choose:
CSV → easy for data exchange.
Excel → best for office use.
Markdown → perfect for docs or GitHub.
👉 how to export as a nicely formatted PDF report (with table borders)?Install once
... ('avocados', 1.25),
... ('bananas', 2.5),
... ('cherries', 15),
... ]
...
... for i, (item, count) in enumerate(pantry):
... print(f"{i} {item} = {count}")
...
0 avocados = 1.25
1 bananas = 2.5
2 cherries = 15
Comments
Post a Comment