2016-12-05 7 views
1

ファイル内の情報からメニューを印刷しようとしているので、情報を取得して辞書を作成しました。私は、値の間隔をフォーマットする方法があるかどうかを調べるために、値をヘッダーに揃えることができます。とにかく、各キーとその値が途中に空白を入れずに印刷されるかどうかを調べようとしています。 私のコードは、現在、次のようになります。印刷辞書の間にformartスペーシングがあります

Output

なぜそれがスペースのないライン後の値ラインを持つ最初の2つのキーを印刷しましたが、:辞書を印刷する場合、出力は次のようになり

#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(" ") 

それらの間に行を持つ他の人ですか?私は各値をそのヘッダーに揃えたいと思う。それは可能ですか?もしそうなら、どのように?私がそうすることができると思う唯一の方法は、印刷機能を使って自分自身をフォーマットすることです。

+1

ランダム推測:あなたの 'item_price'変数に' \ n''がついています。 – CoryKramer

+0

@Maddi、整列した表として印刷したいですか?もしそうなら、 '\ t'を使って視覚化をより良くすることも考えられます。 – lmiguelvargasf

+0

'inventory_list = item.strip()。split("、 ")' –

答えて

0

それぞれのアイテムが異なる長さであるため、それらが整列しない理由があります。各行の最初の項目は、次の項目をもっと長く押すほど右に移動します。私もあなたのinventoryモジュールを持っていないので、それが動作するかどうか、私は確認できない

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() 

これは、これを修正し、あなたのmenu機能の修正版です。

関連する問題