Python新手入门:教你如何绘制整齐的表格。
方法一
代码如下:
print ("+"+"-"*8+"+"+"-"*8+"+"+"-"*8+"+")
print ("|"+" "*2+"姓名"+" "*2+"|"+" "*2+"年龄"+" "*2+"|"+" "*2+"籍贯"+" "*2+"|")
print ("+"+"-"*8+"+"+"-"*8+"+"+"-"*8+"+")
print ("+"+"-"*8+"+"+"-"*8+"+"+"-"*8+"+")
print ("|"+" "*2+"李四"+" "*2+"|"+" "*2+" 45 "+" "*2+"|"+" "*2+"天津"+" "*2+"|")
print ("+"+"-"*8+"+"+"-"*8+"+"+"-"*8+"+")
print ("|"+" "*2+"王五"+" "*2+"|"+" "*2+" 28 "+" "*2+"|"+" "*2+"河北"+" "*2+"|")
print ("+"+"-"*8+"+"+"-"*8+"+"+"-"*8+"+")
效果图如下:
方法二
该方法需要安装prettytable包,类似于和安装pandas包,流程相同。
linuxidc@linuxidc:~/linuxidc.com$ pip3 install prettytable
Collecting prettytable
Downloading https://files.pythonhosted.org/packages/ef/30/4b0746848746ed5941f052479e7c23d2b56d174b82f4fd34a25e389831f5/prettytable-0.7.2.tar.bz2
Building wheels for collected packages: prettytable
Running setup.py bdist_wheel for prettytable ... done
Stored in directory: /home/linuxidc/.cache/pip/wheels/80/34/1c/3967380d9676d162cb59513bd9dc862d0584e045a162095606
Successfully built prettytable
Installing collected packages: prettytable
Successfully installed prettytable-0.7.2
代码如下:
#coding:utf-8
from prettytable import PrettyTable
x= PrettyTable(["姓名", "年龄", "籍贯"])
x.add_row(["张三",32,"北京"])
x.add_row(["李四",45,"天津"])
x.add_row(["王五",28,"河北"])
print(x)
效果如下: