使用字符串打印格式

时间:2014-04-27 18:46:42

标签: string python-3.x

a = [('sample\\assignments.html', 'C:\\Users\\AJ\\Desktop\\sample\\sample\\projects.html', 'sample\\projects.html', False),('sample\\assignments.html','C:\\Users\\AJ\\Desktop\\sample\\sample\\docs-assets\\ico\\favicon.png', 'sample\\docs-assets\\ico\\favicon.png', False)]
print("Broken link")
print("{:>0}{:>35}".format("Source HTML","Link"))
print("============================================================")
for item in a:
   b = list(item)
   print("{:>0}{:>35}".format(b[0],b[2]))

打印结果:

Broken link
Source HTML                          Link
============================================================
sample\assignments.html               sample\projects.html
sample\assignments.html sample\docs-assets\ico\favicon.png
sample\index.html      sample\dist\css\bootstrap.css
sample\testkeys.html            sample\assignments.html
sample\testkeys.html                  sample\index.html

有人可以更正我的代码,以便第二栏中的所有文字"链接"是对齐的,还是排成一列的?

在我的计划中," a" list包含许多元组,其中b [0]和b [2]的长度不同。

我真的不确定。}中的.format()和空格指示符是如何工作的。

由于

1 个答案:

答案 0 :(得分:0)

print("{:<26}{}".format("Source HTML","Link"))
print("="*60)
for item in a:
   b = list(item)
   print("{:<26}{}".format(b[0],b[2]))

输出:

Broken link
Source HTML               Link
============================================================
sample\assignments.html   sample\projects.html
sample\assignments.html   sample\docs-assets\ico\favicon.png