我在下面学习并编写了代码,通过从"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个字符。
您可以使用ljust和rjust
http://www.tutorialspoint.com/python/string_ljust.htmhttp://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())))