一尘不染

格式化控制台输出

python

我在使python打印正确对齐的文本时遇到麻烦。我已经尝试了所有我知道的东西,但是结果还是一样,这很烦人!

这是我在控制台中得到的 在此处输入图片说明

这是我的代码。

print " FileName\t\t\t\t\tStatus\t\tBinary Type\n"

for files in PASS:
    log = subprocess.check_output(['dumpbin','/HEADERS',files])
    if arch64 in log:
        print" %s \t\t\t\tPASSED\t\t 64-bit \t\t  " %files 
    elif arch32 in log:
        print" %s \t\t\t\tPASSED\t\t 32-bit \t\t  " %files
print"\n"   
for files in FAILED:

    print" %s \t\t\t\t  FAILED \t\t        " %files

print "\n\n

阅读 470

收藏
2021-01-20

共1个答案

一尘不染

使用%45s做一个右对齐字段长45个字符。并用于%-45s制作左对齐字符串。还可以考虑将线条打印提取为一个功能-
这样一来,您就可以在一个地方轻松更改它。像这样:

# fake setup 
PASS = ["foo.exe", "bar.exe", "really_long_filename.exe"]
FAILED = ["failed.exe"]
types = ["32-bit", "64-bit", "64-bit"]
arch64 = '64'
arch32 = '32'

# your code
def print_row(filename, status, file_type):
    print " %-45s %-15s %15s" % (filename, status, file_type)

print_row('FileName', 'Status', 'Binary Type')

for files in PASS:
    log = types.pop()
    if arch64 in log:
        print_row(files, 'PASSED', '64-bit')
    elif arch32 in log:
        print_row(files, 'PASSED', '32-bit')
print"\n"

for files in FAILED:
        print_row(files, 'FAILED', '')

print "\n\n"
2021-01-20