前言:基于上次分享(对中国大学排名的爬取)的输出混乱的问题,提出解决办法。
使用replace()方法
-
replace():str.replace(old,new) #old被new替换
-
确定被替换的str

分析:
使用print(u)得到结果,发现输出多了很多不必要的信息,有空格以及/n,所以使用replace()替换解决
改进代码1:
def printUnivList(ulist, num): # 输出结果
print("{0:6s}{1:10s}{2:6s}".format("排名", "学校名称", "总分"))
for i in range(num):
u = ulist[i]
print("{0:6s}{1:10s}{2:6s}".format(u[0].replace(' ', '').replace('
', '').replace('
', ''),
u[1].replace(' ', '').replace('
', '').replace('
', ''),
u[2].replace(' ', '').replace('
', '').replace('
', '')))
结果:

对齐问题的解决
-
上面运行结果不够美观(未对齐)。
-
原因:当中文字符宽度不够时,采用西文字符填充,中西文字符占用的宽度不同。
-
解决办法:统一采用中文字符填充:chr(12288)
改进代码2:
def printUnivList(ulist, num): # 输出结果
tplt = "{0:^10}{1:{3}^20}{2:^10}" #定义输出的模板变量,{3}表示填充时采用第三个字符填充
print(tplt.format("排名", "学校名称", "总分", chr(12288))) #打印头
for i in range(num):
u = ulist[i]
print(tplt.format(u[0].replace(' ', '').replace('
', '').replace('
', ''),
u[1].replace(' ', '').replace('
', '').replace('
', ''),
u[2].replace(' ', '').replace('
', '').replace('
', ''),
chr(12288)))
结果:

调用python美化库(prettytable)
- prettytable:可以将输出内容如表格方式整齐的输出
代码:
def printUnivList(ulist, num): # 输出结果
table = pt.PrettyTable() # 直接创建表
table.field_names = ["排名", "学校名称", "总分"] # 表头字段
for i in range(num):
u = ulist[i]
table.add_row([u[0].replace(' ', '').replace('
', '').replace('
', ''), # 按行添加数据
u[1].replace(' ', '').replace('
', '').replace('
', ''),
u[2].replace(' ', '').replace('
', '').replace('
', '')])
print(table) # 打印表
结果:
