【发布时间】:2017-04-20 08:40:47
【问题描述】:
我正在尝试从文件中的信息打印菜单,因此我获取了信息并创建了字典。我试图弄清楚是否有办法格式化值之间的间距,以便我可以将值与标题对齐。我还试图找出每个键及其值是否会在中间没有一行空格的情况下打印。 我的代码目前如下所示:
#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'。 -
@Maddi,您想将其打印为对齐的表格吗?如果是这样,您还可以考虑使用 '\t' 以获得更好的可视化效果。
-
试试
inventory_list = item.strip().split(",") -
在此处查看更多关于在 python 中格式化表格stackoverflow.com/questions/40933685/…
标签: python dictionary printing format alignment