带有点头的Python打印格式

时间:2015-02-18 16:14:34

标签: python-3.x printing printf string-formatting

如何使用打印格式在两个对象之间放置一组字符(点前导)?

例如,我有以下代码:

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} ON

服务器{SPACE} ............ {SPACE} OFF

2 个答案:

答案 0 :(得分:1)

您可以在将字符串传递给print之前编辑该字符串(编辑后可以获得所需的格式):

  
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"))
  

输出:

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

答案 1 :(得分:0)

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

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