在Python中打印人类可读性的标题信息

时间:2016-05-05 15:26:46

标签: python

我在下面学习并编写了代码,通过从“mylabList.txt”文件中读取主机名来提供主机名及其IP地址,现在我正在寻找以相当人类可读的方式从列中读取输出的方法。每个的顶部然后是名称(在那之下)..

打印时有没有办法在列之间设置宽度......

#!/usr/bin/python

import sys
import socket
with open("mylabList.txt", 'r') as f:

  for host in f:
        print("{0[0]}\t{0[2][0]}".format(socket.gethostbyname_ex(host.rstrip())))

当前输出为:

mylab1.example.com   172.10.1.1
mylab2.example.com   172.10.1.2
mylab3.example.com   172.10.1.3
mylab4.example.com   122.10.1.4

预期输出为:

Server Name     IP ADDRESS
===================================
mylab1.example.com      172.10.1.1
mylab2.example.com      172.10.1.2
mylab3.example.com      172.10.1.3
mylab4.example.com      122.10.1.4

只是一个音符..在我的输出中,Srever Name的长度最多为30个字符。

1 个答案:

答案 0 :(得分:0)

你可以使用ljust和rjust

http://www.tutorialspoint.com/python/string_ljust.htm http://www.tutorialspoint.com/python/string_rjust.htm

print("A String".ljust(30, " ") + "Another String")

结果

A String                      Another String

这是一种可行的方法:

#!/usr/bin/python

import sys
import socket
print("Server Name".ljust(30, " ") + "IP ADRESS")
print("="*39)
with open("mylabList.txt", 'r') as f:
    for host in f:
        print("{0[0]}\t{0[2][0]}".format(socket.gethostbyname_ex(host.rstrip())))