使用prettytable模块来打印99乘法表格

1、prettytable库的安装

[root@Kingstar day08]# pip install prettytable
Collecting prettytable
  Using cached prettytable-0.7.2.tar.bz2 (21 kB)
Installing collected packages: prettytable
    Running setup.py install for prettytable ... done
Successfully installed prettytable-0.7.2

2、99乘法表的实现代码模块

for i in range(1,10):
    for j in range(1,i+1):
        str_obj = '{}*{}={:<3}'.format(j,i,j*i)
        print(str_obj,end=' ')
    print('
')

3、使用prettytable的实现

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from prettytable import PrettyTable

#检查列表的长度是否=9,不等于9用空字符串补齐
def check(list_row):
    if len(list_row) < 9:
        for m in range(1,9-len(list_row)+1):
            list_row.append(' ')
    return list_row

def main():
    #实例化一个对象
    tb = PrettyTable()
    #设置表头
    tb.field_names = ['第{}列'.format(i) for i in range(1,10)]  
    for i in range(1,10):
        list_row = []
        for j in range(1,i+1):
            list_row.append('{}*{}={:<3}'.format(j,i,j*i))
        list_row = check(list_row)
        tb.add_row(list_row)
    print(tb)

if __name__ == '__main__':
    main()

实现效果如下所示:

4、prettytable模块的一些其他设置

设置某一列元素的对其方式:

 tb_shop.align['商品名称'] = 'l'    设置对齐
 tb_shop.align['商品单价'] = 'c'   设置居中对齐
 tb_shop.align['商品数量'] = 'c'
 tb_shop.align['金额小计'] = ' r'   设置右对齐

对列表按照某一列进行排序:

 print(tb.get_string(sortby='商品价格',reversesort=True)) #对商品列表进行排序

5、购物车小程序的实现代码:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from prettytable import PrettyTable

msg_dic = {'apple':10,
           'tesla':100000,
           'mac':3000,
           'lenovo':30000,
           'chicken':10}

def main():
    goods_info = []
    total = 0
    while 1:
        tb = PrettyTable()
        tb.field_names = ['商品名称','商品价格']
        tb.align['商品名称'] = 'l'   # 以“商品名称”字段左对齐
        tb.align['商品价格'] = 'c'   # 以“商品价格字段”居中对齐
        for k,v in msg_dic.items():
            tb.add_row([k,v])
        print(tb.get_string(sortby='商品价格',reversesort=True)) #对商品列表进行排序
        goods_choice = input('请输入你要购买的商品:').strip()
        if goods_choice in msg_dic.keys():
            num_choice = int(input('请输入购买{}的数量:'.format(goods_choice)))
            goods_info.append([goods_choice,msg_dic.get(goods_choice),num_choice])
            _continue = input('购买成功,是否继续添加商品(y,n):').strip().lower()
            if _continue == 'y':
                continue
            else:
                print('用户选择n或者输入其他非法字符,退出!')
                break
        else:
            print('输入为空或者其他非法字符,请重新输入!')
    #输出购物车信息
    tb_shop = PrettyTable()
    tb_shop.field_names = ['商品名称','商品单价','商品数量','金额小计']
    tb_shop.align['商品名称'] = 'l'
    tb_shop.align['商品单价'] = 'c'
    tb_shop.align['商品数量'] = 'c'
    tb_shop.align['金额小计'] = 'c'
    for item in goods_info:
        name_of_goods,price_of_goods,num_of_goods = item
        sum_of_money = price_of_goods * num_of_goods
        total += sum_of_money
        tb_shop.add_row([name_of_goods,price_of_goods,num_of_goods,sum_of_money])
    print(tb_shop.get_string(sortby='金额小计',reversesort=True))
    print('您一共消费{}元,欢迎下次光临!'.format(total))

if __name__ == '__main__':
    main()
原文地址:https://www.cnblogs.com/surpass123/p/12492120.html