当前位置: 动力学知识库 > 问答 > 编程问答 >

Python - Formatting a print to align a specific column

问题描述:

I am trying to format a print statement to align a specific column.

Currently my output is:

0 - Rusty Bucket (40L bucket - quite rusty) = $0.00

1 - Golf Cart (Tesla powered 250 turbo) = $195.00*

2 - Thermomix (TM-31) = $25.50*

3 - AeroPress (Great coffee maker) = $5.00

4 - Guitar (JTV-59) = $12.95

The output I am looking for is:

0 - Rusty Bucket (40L bucket - quite rusty) = $0.00

1 - Golf Cart (Tesla powered 250 turbo) = $195.00*

2 - Thermomix (TM-31) = $25.50*

3 - AeroPress (Great coffee maker) = $5.00

4 - Guitar (JTV-59) = $12.95

Here is the code I am currently using for the print:

def list_items():

count = 0

print("All items on file (* indicates item is currently out):")

for splitline in all_lines:

in_out = splitline[3]

dollar_sign = "= $"

daily_price = "{0:.2f}".format(float(splitline[2]))

if in_out == "out":

in_out = str("*")

else:

in_out = str("")

print(count, "- {} ({}) {}{}{}".format(splitline[0], splitline[1], dollar_sign, daily_price, in_out))

count += 1

I have tried using formatting such as:

print(count, "- {:>5} ({:>5}) {:>5}{}{}".format(splitline[0], splitline[1], dollar_sign, daily_price, in_out))

but have never been able to get just the one column to align. Any help or suggestions would be greatly appreciated! I am also using python 3.x

To note I am using tuples to contain all the information, with all_lines being the master list, as it were. The information is being read from a csv originally. Apologies for the horrible naming conventions, trying to work on functionality first.

Sorry if this has been answered elsewhere; I have tried looking.

EDIT: Here is the code im using for my all_lines

import csv

open_file = open('items.csv', 'r+')

all_lines = []

for line in open_file:

splitline = line.strip().split(',')

all_lines.append((splitline[0], splitline[1], splitline[2], splitline[3]))

And here is the csv file information:

Rusty Bucket,40L bucket - quite rusty,0.0,in

Golf Cart,Tesla powered 250 turbo,195.0,out

Thermomix,TM-31,25.5,out

AeroPress,Great coffee maker,5.0,in

Guitar,JTV-59,12.95,in

网友答案:

What you are looking for may be:

[EDIT] I have now also included a tabulate version since you may gain flexibility with this.

import csv
from tabulate import tabulate
open_file = open('items.csv', 'r+')
all_lines = []
for line in open_file:
    splitline = line.strip().split(',')
    all_lines.append((splitline[0], splitline[1], splitline[2], splitline[3]))

#print all_lines
count = 0
new_lines=[]
for splitline in all_lines:
    in_out = splitline[3]
    dollar_sign = "= $"
    daily_price = "{0:.2f}".format(float(splitline[2]))
    if in_out == "out":
        in_out = str("*")
    else:
        in_out = str("")
    str2='('+splitline[1]+')'    
    print count, "- {:<30} {:<30} {}{:<30} {:<10}".format(splitline[0], str2, dollar_sign, daily_price, in_out)
    new_lines.append([splitline[0], str2, dollar_sign, daily_price, in_out])
    count += 1

print tabulate(new_lines, tablefmt="plain")
print
print tabulate(new_lines, tablefmt="plain", numalign="left")
网友答案:

You should look at str.ljust(width[, fillchar]):

> '(TM-31)'.ljust(15)
'(TM-31)        '  # pad to width

Then extract the variable-length {} ({}) part and padd it to the necessary width.

网友答案:

I do not like the idea of controlling printing format myself.

In this case, I would leverage a tabulating library such as: Tabulate.

The two key points are:

  1. keep data in a table (e.g. list in a list)
  2. select proper printing format with tablefmt param.
分享给朋友:
您可能感兴趣的文章:
随机阅读: