2016-12-05 28 views
1

我试图从文件内的信息打印菜单,所以我拿走了信息并创建了一本字典。我试图找出是否有方法来格式化值之间的间距,所以我可以将值与标头对齐。我还试图找出是否有任何关键字及其值将在中间没有空格的情况下打印。 我的代码目前看起来是这样的:打印字典之间的formart间距

#import classes 
import inventory 


#define constant for file 
INVENTORY = "inventory.txt" 

#define main 
def main(): 
    #create empty dictionary to fill later 
    inventory_dict = {} 
    #call function to process inventory 
    process_inventory(inventory_dict) 
    #call function to print menu 
    menu(inventory_dict) 


#define process file inventory function 
def process_inventory(inventory_dict): 

    #open inventory file 
    inventory_file = open(INVENTORY, 'r') 

    #create inventory instances 
    for item in inventory_file: 

     #split line to reash 
     inventory_list = item.split(",") 

     #create variables to store each quality 
     item_id = inventory_list[0] 
     item_name = inventory_list[1] 
     item_qty = inventory_list[2] 
     item_price = inventory_list[3] 

     #create object 
     product = inventory.Inventory(item_id,item_name,item_qty,item_price) 

     #add qualities to inventory dictionary 
     inventory_dict[item_id] = product 

    #close file 
    inventory_file.close() 

#define function to print menu 
def menu(inventory_dict): 
    #print headers 
    print("ID Item Price Qty Avaliable") 

    #print object information 
    for object_id in inventory_dict: 
     print(inventory_dict[object_id]) 

    #print how to exit 
    print("Enter 0 when finished") 

    #print blank line 
    print(" ") 

当打印输出看起来像词典:

Output

为什么会打印与价值线前两个键行后没有空间,但其他与之间的线?我想将每个值与它的标题对齐。那可能吗?如果是这样如何?我能想到的唯一方法就是使用打印功能并自己设置格式。

+1

随机猜测:你的'item_price'变量有一个''\ n''尾随它。 – CoryKramer

+0

@Maddi,你想打印它作为一个对齐的表?如果是这样,你也可以考虑使用'\ t'有一个更好的可视化。 – lmiguelvargasf

+0

尝试'inventory_list = item.strip()。split(“,”)' –

回答

0

他们不对齐的原因是因为每个项目是不同的长度。每行中的第一项将时间越长的下一个项目向右推。

这是你menu功能的修改版本,修复此:

def menu(inventory_dict): 
    maxLength = 0 
    for row in inventory_dict.values(): 
     for item in row.values(): 
      maxLength = max(len(item), maxLength) # If the item is longer than our current longest, make it the longest 
    #print headers 
    for header in ("ID", "Item", "Price", "Qty", "Avaliable"): 
     print(header.ljust(maxLength)) # Fill spaces in until the header is as long as our longest item 
    print() 

    #print object information 
    for row in inventory_dict.values(): 
     for item in row.values(): 
      print(item.ljust(maxLength)) # Fill spaces in until the header is as long as our longest item 

    #print how to exit 
    print("Enter 0 when finished") 

    #print blank line 
    print() 

我无法验证,如果它的作品,因为我没有你inventory模块虽然。