Python 带点前导的打印格式

Python print format with dot leader

如何使用打印格式在 2 个对象之间放置一组字符(以点开头)?

比如我有如下代码:

os.chdir( "LOGS\" )
for file in glob.glob('*'):
    with open(file) as f:
        contents = f.read()
    if 'HOST_POWER="ON"' in contents:
        print('{0:38} {1:3}'.format(file[:-4]," = ON"))

for file in glob.glob('*'):
    with open(file) as f:
        contents = f.read()
    if 'HOST_POWER="OFF"' in contents:
        print('{0:38} {1:3}'.format(file[:-4]," = OFF"))

输出:

server1.web.com          = ON
server2.web.com          = ON
server3334.web.com       = OFF
server5332223.web.com    = ON
server2233.web.com       = ON
server44.web.com         = ON
server1133333.web.com    = OFF

但我希望输出看起来像这样:

server1.web.com ............ ON
server2.web.com ............ ON
server3334.web.com ......... OFF
server5332223.web.com ...... ON
server2233.web.com ......... ON
server44.web.com ........... ON
server1133333.web.com ...... OFF

服务器{SPACE}................{SPACE}开启

服务器{SPACE}................{SPACE}关闭

您可以在将字符串传递给打印之前对其进行编辑(进行编辑以获得您想要的格式):

import glob

def padStr( x, n ):
    x += ' '
    return x + '.'*(n - len(x) )

for file in glob.glob('*.*'):
    with open(file) as f:
        contents = f.read()
    if 'HOST_POWER="OFF"' in contents:
        print('%s %s' % ( padStr(file[:-4], 38 ),"ON"))

for file in glob.glob('*'):
    with open(file) as f:
        contents = f.read()
    if 'HOST_POWER="OFF"' in contents:
        print('%s %s' % ( padStr(file[:-4], 38 ),"OFF"))

Output:

blahblahblah ......................... ON
f1 ................................... ON
tes .................................. OFF

另一个(稍微混乱的)选项是在将字符串用作格式 arg 之前将其固定在行中:

print('{0} {1:3}'.format((f[:-4]+' ').ljust(38, '.'),"= ON"))