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(" ")
當打印輸出看起來像詞典:
爲什麼會打印與價值線前兩個鍵行後沒有空間,但其他與之間的線?我想將每個值與它的標題對齊。那可能嗎?如果是這樣如何?我能想到的唯一方法就是使用打印功能並自己設置格式。
隨機猜測:你的'item_price'變量有一個''\ n''尾隨它。 – CoryKramer
@Maddi,你想打印它作爲一個對齊的表?如果是這樣,你也可以考慮使用'\ t'有一個更好的可視化。 – lmiguelvargasf
嘗試'inventory_list = item.strip()。split(「,」)' –